In the following code, the first test passes, and the second one does not, which I find puzzling.
import paramiko
def test1():
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect('10.0.0.107', username='test', password='test')
sftp = client.open_sftp()
sftp.stat('/tmp')
sftp.close()
def get_sftp():
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect('10.0.0.107', username='test', password='test')
return client.open_sftp()
def test2():
sftp = get_sftp()
sftp.stat('/tmp')
sftp.close()
if __name__ == '__main__':
test1()
print 'test1 done'
test2()
print 'test2 done'
Here's what I get:
$ ./script.py
test1 done
Traceback (most recent call last):
File "./play.py", line 25, in <module>
test2()
File "./play.py", line 20, in test2
sftp.stat('/tmp')
File "/usr/lib/pymodules/python2.6/paramiko/sftp_client.py", line 337, in stat
t, msg = self._request(CMD_STAT, path)
File "/usr/lib/pymodules/python2.6/paramiko/sftp_client.py", line 627, in _request
num = self._async_request(type(None), t, *arg)
File "/usr/lib/pymodules/python2.6/paramiko/sftp_client.py", line 649, in _async_request
self._send_packet(t, str(msg))
File "/usr/lib/pymodules/python2.6/paramiko/sftp.py", line 172, in _send_packet
self._write_all(out)
File "/usr/lib/pymodules/python2.6/paramiko/sftp.py", line 138, in _write_all
raise EOFError()
EOFError
This happens both on Ubuntu (Python 2.6 and paramiko 1.7.6) and Debian (Python 2.7 and paramiko 1.7.7).
If I run test2 first, I only get the stack trace, meaning test2 indeed fails.
Ok, I've verified it on debian/python2.6/paramiko1.7.6.
The reason is that the client object goes out of scope in get_sftp (and closes the "channel"). If you cange it so you return the client:
import paramiko
def get_sftp():
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect('localhost', username='root', password='B4nan-purr(en)')
return client
def test2():
client = get_sftp()
sftp = client.open_sftp()
sftp.stat('/tmp')
sftp.close()
if __name__ == "__main__":
test2()
then everything will work (the function name should probably be changed..).
Related
I have tried to fix it up but got the same error every time. I have tried several times also tried in google but cannot give a suitable answer.
def ssh(hostname, command):
sshcon = paramiko.SSHClient()
logging.basicConfig()
sshcon.load_system_host_keys()
sshcon.set_missing_host_key_policy(paramiko.AutoAddPolicy())
sshcon.connect(hostname, username='root', password='password')
stdin, stdout, stderr = sshcon.exec_command(command)
return stdout.read()
while True:
i = 1
while i <= 60:
print "|------- Webserver2 -----------|"
print time.ctime()
response_time(desired_response_time, url2, webserver2, bilal2, local)
list=ssh(bilal2, "xm list")
if "webserver1" in list:
horizontal('2')
print "|------- Webserver1 -----------|"
response_time(desired_response_time, url1, webserver1, bilal2, local)
else:
horizontal('1')
pass
time.sleep(5)
i += 1
The error
Error:
Traceback (most recent call last):
File "newcodepid.py", line 472, in <module>
list=ssh(bilal2, "xm list")
File "newcodepid.py", line 61, in ssh
sshcon.connect(hostname, username='root', password='password')
File "/usr/lib/python2.7/dist-packages/paramiko/client.py", line 332, in connect
self._auth(username, password, pkey, key_filenames, allow_agent, look_for_keys)
File "/usr/lib/python2.7/dist-packages/paramiko/client.py", line 493, in _auth
raise saved_exception
paramiko.AuthenticationException: Authentication failed.
My code:
#!/usr/bin/env python3
from paramiko.client import SSHClient, WarningPolicy
HOST_NAME = "********"
USER_NAME = "********"
PASSWD = "********"
def ssh_setup():
client = SSHClient()
client.load_system_host_keys()
client.set_missing_host_key_policy(WarningPolicy)
client.connect(HOST_NAME, 22, USER_NAME, PASSWD)
return client
def main():
client = ssh_setup()
client.exec_command("DISPLAY=:0.0 notify-send \"Test\"")
client.close()
if __name__ == "__main__":
main()
When ran, I get the following error:
Traceback (most recent call last):
File "./test", line 30, in <module>
main()
File "./test", line 25, in main
client = ssh_setup()
File "./test", line 20, in ssh_setup
client.connect(HOST_NAME, 22, USER_NAME, PASSWD)
File "/usr/local/lib/python3.4/dist-packages/paramiko/client.py", line 348, in connect
server_key)
TypeError: missing_host_key() missing 1 required positional argument: 'key'
I can ssh into the machine in question just fine (I mean, "I don't even need to enter my password" fine)
You need to pass the WarningPolicy object to set_missing_host_key_policy
client.set_missing_host_key_policy(WarningPolicy())
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 need to upload some files using SFTP, this works from the command line:
$sftp myuser#my_remote_host
Connected to my_remote_host
sftp>
This is my Paramiko script:
#!/usr/bin/env python
import paramiko
import sys
import os
host = "my_remote_host"
port = 22
transport = paramiko.Transport((host, port))
username = "myuser"
LOCAL_PATH = "/tmp/"
REMOTE_PATH = "/dcs/tmp/"
FILE = "myfile"
transport.connect(username = username)
sftp = paramiko.SFTPClient.from_transport(transport)
path = LOCAL_PATH + FILE
sftp.put(LOCAL_PATH + FILE, REMOTE_PATH + FILE)
sftp.close()
transport.close()
print 'Upload done.'
When executing I get this error:
No handlers could be found for logger "paramiko.transport"
Traceback (most recent call last):
File "./my_sftp.py", line 19, in ?
sftp = paramiko.SFTPClient.from_transport(transport)
File "/usr/lib/python2.4/site-packages/paramiko/sftp_client.py", line 102, in from_transport
chan = t.open_session()
File "/usr/lib/python2.4/site-packages/paramiko/transport.py", line 655, in open_session
return self.open_channel('session')
File "/usr/lib/python2.4/site-packages/paramiko/transport.py", line 745, in open_channel
raise e
EOFError
When adding a private key I get this error:
path = os.path.join(os.environ['HOME'], '.ssh', 'id_dsa')
key = paramiko.DSSKey.from_private_key_file(path)
transport.connect(username = username, pkey=key)
Traceback (most recent call last):
File "./my_sftp.py", line 24, in ?
transport.connect(username = username, pkey=key)
File "/usr/lib/python2.4/site-packages/paramiko/transport.py", line 1007, in connect
self.auth_publickey(username, pkey)
File "/usr/lib/python2.4/site-packages/paramiko/transport.py", line 1234, in auth_publickey
return self.auth_handler.wait_for_response(my_event)
File "/usr/lib/python2.4/site-packages/paramiko/auth_handler.py", line 174, in wait_for_response
raise e
paramiko.AuthenticationException: Authentication failed.
In your first example, you can't authenticate with only a username, so the session can't be started.
I can't tell why your privatekey example isn't working without some more information. Is it possible that its the incorrect key for that server? SSH on the command line may be trying multiple keys, or getting it from an agent.
Anyway, it easier to start off with the SSHClient class. It will wrap up all the authentication, and host verification pieces in one package. It also has an open_sftp() convenience method to return an SFTPClient instance.