I want to run simple command just for test ssh connection. There is an error about stdin/out/err. Code and error mesage is below.
Can someone help me ?
Code
import paramiko
import sys
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect('x.x.x.x', port=2222, username='user', password='pass')
stdin, stdout, stderr = client.exec_command('exit')
print stdout
client.close()
Error message
Traceback (most recent call last):
File "C:/Users/EXT03D3912/PycharmProjects/paramiko_ssh1/paramiko_ssh1.py", line 9, in <module>
stdin, stdout, stderr = client.exec_command('exit')
File "build\bdist.win32\egg\paramiko\client.py", line 343, in exec_command
File "build\bdist.win32\egg\paramiko\channel.py", line 212, in exec_command
File "build\bdist.win32\egg\paramiko\channel.py", line 1081, in _wait_for_event
EOFError
thanks,
haktan
Since you are logged out from the terminal it is giving a EOFError AFAIK you can just close the connection it will automatically close your session there.
Consider the following code
import paramiko
import sys
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect('x.x.x.x', port=2222, username='user', password='pass')
stdin, stdout, stderr = client.exec_command('ls')
print stdout
client.close()
Related
I've found the following script on internet:
import paramiko
from paramiko import client
class ssh:
client = None
def __init__(self, address, username, password):
# Let the user know we're connecting to the server
print("Connecting to server.")
# Create a new SSH client
self.client = client.SSHClient()
# The following line is required if you want the script to be able to access a server that's not yet in the known_hosts file
self.client.set_missing_host_key_policy(client.AutoAddPolicy())
# Make the connection
self.client.connect(address, username=username, password=password, look_for_keys=False)
def sendCommand(self, command):
# Check if connection is made previously
if (self.client):
stdin, stdout, stderr = self.client.exec_command(command)
while not stdout.channel.exit_status_ready():
# Print stdout data when available
if stdout.channel.recv_ready():
# Retrieve the first 1024 bytes
alldata = stdout.channel.recv(1024)
while stdout.channel.recv_ready():
# Retrieve the next 1024 bytes
alldata += stdout.channel.recv(1024)
# Print as string with utf8 encoding
print(str(alldata, "utf8"))
else:
print("Connection not opened.")
paramiko.util.log_to_file('paramiko.log') # <----- added line
connessione = ssh("10.76.80.11","pi","raspberry")
connessione.sendCommand("arp -a")
I would like to send a commando to my raspberry with this script, I tried to run the program without the line:
paramiko.util.log_to_file('paramiko.log')
but when I tried to run the code I've got this runtime error:
/usr/bin/python /Users/Marco/PycharmProjects/ssh_control/ssh.py
Connecting to server.
No handlers could be found for logger "paramiko.transport"
Traceback (most recent call last):
File "/Users/Marco/PycharmProjects/ssh_control/ssh.py", line 43, in <module>
connessione = ssh("10.76.80.11","pi","raspberry")
File "/Users/Marco/PycharmProjects/ssh_control/ssh.py", line 16, in __init__
self.client.connect(address, username=username, password=password, look_for_keys=False)
File "/Users/Marco/Library/Python/2.7/lib/python/site-packages/paramiko/client.py", line 338, in connect
t.start_client()
File "/Users/Marco/Library/Python/2.7/lib/python/site- packages/paramiko/transport.py", line 493, in start_client
raise e
AttributeError: 'EntryPoint' object has no attribute 'resolve'
Process finished with exit code 1
So I searched on Internet and I found that the problem could be fixed with the paramiko.log line.
But now I've another error:
/usr/bin/python /Users/Marco/PycharmProjects/ssh_control/ssh.py
Connecting to server.
Traceback (most recent call last):
File "/Users/Marco/PycharmProjects/ssh_control/ssh.py", line 38, in <module>
connessione = ssh("10.76.80.11","pi","raspberry")
File "/Users/Marco/PycharmProjects/ssh_control/ssh.py", line 16, in __init__
self.client.connect(address, username=username, password=password, look_for_keys=False)
File "/Users/Marco/Library/Python/2.7/lib/python/site- packages/paramiko/client.py", line 338, in connect
t.start_client()
File "/Users/Marco/Library/Python/2.7/lib/python/site-packages/paramiko/transport.py", line 493, in start_client
raise e
AttributeError: 'EntryPoint' object has no attribute 'resolve'
Process finished with exit code 1
Can someone helps me please? because I can't understand where is the error.
Thanks in advance
Turns out you need to upgrade setuptools and then re-install the package. Seems the older version breaks something on installing the python cryptography package.
Try the following...
pip install -U setuptools
pin install -U paramiko
https://github.com/pyca/cryptography/issues/2853
I solved my problem with this:
# Make the connection
self.client.connect(address, port = 22, username=username, password=password, look_for_keys=False)
because the port before wasn't specificate
I try to return socket object from function, but after return socket immediatly closes. Any help is greatly appreciated :) Thanks
def get_connection(ip, log, paswd):
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(ip, username=log, password=paswd, timeout=100)
console = ssh.invoke_shell()
print(console)
return console
def get_version(console, host):
promt = console.recv(1000)
if '>' in str(promt):
console.send('enable\n')
console.send('P#ssw0rd\n')
console.send('terminal length 0\n')
console.send('show version\n')
time.sleep(2)
out = console.recv(5000).decode('utf-8')
system_version_finder = re.search('#show version\r\n(.+)', out)
if system_version_finder:
system_version = system_version_finder.group(1)
else:
system_version = 'Unknown'
print(host + '\s' + system_version)
def upload_config(console, file_path):
console.send('configure terminal\n')
with open(file_path, 'r') as config_file:
for line in config_file:
console.send(line)
for host in options.ip_address_list:
console = get_connection(host, options.login, options.password)
print(console)
get_version(console, host)
if options.conf_file_path:
upload_config(console, options.conf_file_path)
This is output of script:
<paramiko.Channel 0 (open) window=1024 -> <paramiko.Transport at 0x34f5e10 (cipher aes128-cbc, 128 bits) (active; 1 open channel(s))>>
<paramiko.Channel 0 (closed) -> <paramiko.Transport at 0x34f5e10 (unconnected)>>
Traceback (most recent call last):
File "llearn.py", line 65, in <module>
get_version(console, host)
File "llearn.py", line 32, in get_version
console.send('terminal length 0\n')
File "C:\Program Files (x86)\Python\lib\site-packages\paramiko-1.16.0-py3.4.egg\paramiko\channel.py", line 698, in send
File "C:\Program Files (x86)\Python\lib\site-packages\paramiko-1.16.0-py3.4.egg\paramiko\channel.py", line 1058, in _send
OSError: Socket is closed
Hmm, I think the contents of ssh in get_connection might be garbage collected after the function returns, because paramiko isn't holding on to it in console.
Try:
def get_connection(ip, log, paswd):
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(ip, username=log, password=paswd, timeout=100)
console = ssh.invoke_shell()
console.keep_this = ssh
print(console)
return console
Note we're now storing a reference to ssh on console.
On FreeBSD, your version doesn't produce errors, but it doesn't seem to work either. Adding that line makes it work for me.
I wrote a python program. I have conf file, I wrote router configuration commands inside the conf file and I want to execute these commands inside paramiko. I have a problem - the error message is below. Can you help me please ?
CODE:
#!/usr/bin/env python
import paramiko
ip="10.100.1.200"
ssh=paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(ip,username="admin",password="pass")
text=open("conf")
for komut in text.readlines():
stdin, stdout, stderror = ssh.exec_command(komut)
for line in stdout.readlines():
print line.strip()
ssh.close()
text.close()
error message:
Traceback (most recent call last):
File "./configmaker.py", line 13, in <module>
stdin, stdout, stderror = ssh.exec_command(str(komut.strip()))
File "/usr/lib/python2.7/dist-packages/paramiko/client.py", line 370, in exec_command
chan = self._transport.open_session()
File "/usr/lib/python2.7/dist-packages/paramiko/transport.py", line 662, in open_session
return self.open_channel('session')
File "/usr/lib/python2.7/dist-packages/paramiko/transport.py", line 764, in open_channel
raise e
EOFError
Try with this code:
import paramiko
if __name__ == "__main__":
ip = "127.0.0.1"
username = "admin"
password = "root"
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(ip,username=username,password=password)
ssh_transport = ssh.get_transport()
for command in ("ls /tmp", "date"):
chan = ssh_transport.open_session()
chan.exec_command(command)
exit_code = chan.recv_exit_status()
stdin = chan.makefile('wb', -1) # pylint: disable-msg=W0612
stdout = chan.makefile('rb', -1)
stderr = chan.makefile_stderr('rb', -1) # pylint: disable-msg=W0612
output = stdout.read()
print output
Try this code, first copy the conf file to remote server and execute the file.
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
host = str(host)
user = 'root'
pw = 'root123'
ssh.connect(host, username=user, password=pw)
filepath = "conf"
remote_path = "/root/qats_tool.tar"
sftp = ssh.open_sftp()
sftp.put(filepath, remote_path)
command="./conf"
stdin, stdout, stderr = ssh.exec_command(command)
sftp.close()
I try to use python 2.7.1 and paramiko 1.12.0:
connection = paramiko.SSHClient()
connection.load_host_keys(os.path.expanduser(os.path.join("~", ".ssh", "known_hosts")))
connection.set_missing_host_key_policy(paramiko.AutoAddPolicy())
connection.connect(hostIP, 22, 'd', 'd')
command = 'ls'
(stdin, stdout, stderr) = connection.exec_command(command)
response = stdout.readlines()
errormsg = stderr.read()
But I get this error message:
Traceback (most recent call last):<br>
File "./ssh.py", line 32, in <module><br>
(stdin, stdout, stderr) = connection.exec_command(command)<br>
File "/app/python/2.7.1/LMWP3/lib/python2.7/site-packages/paramiko/client.py", line 379, in exec_command<br>
chan.exec_command(command)<br>
File "/app/python/2.7.1/LMWP3/lib/python2.7/site-packages/paramiko/channel.py", line 218, in exec_command<br>
self._wait_for_event()<br>
File "/app/python/2.7.1/LMWP3/lib/python2.7/site-packages/paramiko/channel.py", line 1129, in _wait_for_event<br>
raise e<br>
paramiko.SSHException: Channel closed.
import paramiko
s = paramiko.SSHClient()
s.set_missing_host_key_policy(paramiko.AutoAddPolicy())
conn = s.connect(hostIP, username ='root', password='rootpassword', port=22)
command = 'pwd'
(stdin, stdout, stderr) = s.exec_command(command)
print stdout.read()
s.close()
This should work fine with root user on linux. If it's not, you are probably passing wrong values for hostIP (for ex: quotes in the value), username, password.
I am using Python's paramiko package to connect to a remote Unix machine. I have written this code:
import paramiko
import sys
import os
import os.path
passwd = "XXX"
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect("173.15.13.28", "root", password=passwd)
stdin, stdout, stderr = ssh.exec_command('ls')
x = stdout.readlines()
print x
for line in x:
print line
ssh.close()
after executing I am getting this error:
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
ssh.connect("173.15.13.28", "root", password="--------")
File "C:\Python27\lib\site-packages\paramiko\client.py", line 282, in connect
for (family, socktype, proto, canonname, sockaddr) in socket.getaddrinfo(hostname, port,socket.AF_UNSPEC, socket.SOCK_STREAM):
gaierror: [Errno 10109] getaddrinfo failed
I don't know what the problem is.
The second argument of the connect() method is the port number, which defaults to 22. You are putting "root" there, which won't work. Use the keyword argument username="root". That is, try this:
ssh.connect("173.15.13.28", username="root", password=passwd)
See also: python paramiko, getaddrinfo error when trying to establish an SSH connection