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())
Related
I'm working on mail application and encountering a big problem with Python imaplib.
Here is the code that I try to use to login to mail server.
M = imaplib.IMAP4(self.server,int(self.port))
M.login(self.user, self.password)
I'm using "port 143", "useSLL = false", no secure.
And here is the message that I receive when trying to login to server.
DEBUG:root:Login failed.
Traceback (most recent call last):
File "/opt/splunk/etc/apps/IMAPmailbox/bin/get_imap_email.py", line 347, in getMail
M.login(self.user, self.password)
File "/opt/splunk/lib/python2.7/imaplib.py", line 520, in login
raise self.error(dat[-1])
error: Login failed.
None
Traceback (most recent call last):
File "/opt/splunk/etc/apps/IMAPmailbox/bin/get_imap_email.py", line 724, in <module>
parseArgs()
File "/opt/splunk/etc/apps/IMAPmailbox/bin/get_imap_email.py", line 716, in parseArgs
imapProc.getMail()
File "/opt/splunk/etc/apps/IMAPmailbox/bin/get_imap_email.py", line 352, in getMail
raise LoginError('Could not log into server: %s with password provided' % self.server)
__main__.LoginError: Could not log into server: (my server) with password provided
p/s: I have another mail application which get emails throw imap on ruby and it's working fine with port 143 no secure.
Anyone please help me to solve this problem. Thanks
Use this instead
M = imaplib.IMAP4_SSL(self.server,int(self.port))
M.login(self.user, self.password)
I am using imaplib.IMAP4_SSL instead of imaplib.IMAP4and this seems to work for me
I got a solution which work for both gmail and Outlook
def connect(self, username, password):
if self.tls:
self.server.starttls()
if(self.hostname == 'imap.outlook.com'):
imap_server = "outlook.office365.com"
self.server = self.transport(imap_server, self.port)
self.server = imaplib.IMAP4_SSL(imap_server)
(retcode, capabilities) = self.server.login(username,password)
self.server.select('inbox')
else:
typ, msg = self.server.login(username, password)
if self.folder:
self.server.select(self.folder)
else:
self.server.select()
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.
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..).
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 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.