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
Related
I am trying to connect and upload / download a text file via Python, but I am getting this error:
Traceback (most recent call last):
File "C:\Users\Abdul\OneDrive\Desktop\SFTP neu\main3.py", line 8, in <module>
c.connect(hostname = "0.0.0.0",port = 22, username = "tester", pkey = k)
File "D:\Python\lib\site-packages\paramiko\client.py", line 349, in connect
retry_on_signal(lambda: sock.connect(addr))
File "D:\Python\lib\site-packages\paramiko\util.py", line 283, in retry_on_signal
return function()
File "D:\Python\lib\site-packages\paramiko\client.py", line 349, in <lambda>
retry_on_signal(lambda: sock.connect(addr))
OSError: [WinError 10049] Die angeforderte Adresse ist in diesem Kontext ungültig
I'm using Rebex TinySFTP Server.
At first I thought my host was wrong, but that wasn't it.
In this example I used 0.0.0.0.
Here is my code:
#!/usr/bin/python3
import paramiko
k = paramiko.RSAKey.from_private_key_file("C:\\Users\\Abdul\\OneDrive\\Desktop\\RebexServer\\private-rsa-key.pem")
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
print("connecting")
c.connect(hostname = "0.0.0.0",port = 22, username = "tester", pkey = k)
print("connected")
commands = ["C:\\Users\\Abdul\\OneDrive\\Desktop\\RebexServer\\data\\testfile.txt", "C:\\Users\\Abdul\\OneDrive\\Desktop\\SFTP neu\\data\\testfile1.txt"]
for command in commands:
print("Executing {0}".format( command ))
stdin , stdout, stderr = c.exec_command(command)
print(stdout.read())
print("Errors")
print(stderr.read())
c.close()
At first I thought my host was wrong, but that wasn't it. In this example I used 0.0.0.0
0.0.0.0 is often used when starting a server to indicate that the server should bind to all available IP addresses. But it's not what you should use in your client.
Use one of the actual IP addresses your server is binding to. If both are on the same machine, try 127.0.0.1 or whatever IP address you are using locally. Addresses starting with 192.168. are common in home and small office networks.
I'm just building my first login to a device script, and am having some issues, im getting the below error, all i have changed is the port no, but the issue seems to be with login, i have entered the correct user pass thats for sure.
Error:
Traceback (most recent call last):
File "ssh.py", line 11, in <module>
conn.login(account) # Authenticate on the remote host
File "/usr/local/lib/python2.7/dist-packages/Exscript-2.1.503-py2.7.egg/Exscript/protocols/Protocol.py", line 627, in login
self.authenticate(account, flush = False)
File "/usr/local/lib/python2.7/dist-packages/Exscript-2.1.503-py2.7.egg/Exscript/protocols/Protocol.py", line 651, in authenticate
self.app_authenticate(app_account, flush = flush)
File "/usr/local/lib/python2.7/dist-packages/Exscript-2.1.503-py2.7.egg/Exscript/protocols/Protocol.py", line 819, in app_authenticate
self._app_authenticate(account, password, flush, bailout)
File "/usr/local/lib/python2.7/dist-packages/Exscript-2.1.503-py2.7.egg/Exscript/protocols/Protocol.py", line 723, in _app_authenticate
raise TimeoutException(msg)
Exscript.protocols.Exception.TimeoutException: Buffer: ''
Config:
import hashlib
import Exscript
from Exscript.util.interact import read_login
from Exscript import Account
from Exscript.protocols import SSH2
account = read_login() # Prompt the user for his name and password
conn = SSH2() # We choose to use SSH2
conn.connect('10.66.118.250', 3008) # Open the SSH connection to port
conn.login(account) # Authenticate on the remote host
conn.execute('enable')
conn.execute('conf t')
conn.execute('interface g0/0/1')
conn.execute('description *** TEST ***')
conn.execute('end')
print conn.response
conn.execute('show ip route')
print conn.response
conn.send('exit\r') # Send the "exit" command
conn.close()
This is my code, to delete a remote directory using paramiko sftp.
import paramiko
host = "192.168.1.13"
port = 22
transport = paramiko.Transport((host, port))
username = "root"
password = "abc123"
transport.connect(username = username, password = password)
sftp = paramiko.SFTPClient.from_transport(transport)
filepath = '/root/test_folder'
sftp.rmdir(filepath)
Execute above code will output this error,
Traceback (most recent call last):
File "autom_test.py", line 36, in <module>
sftp.rmdir(filepath)
File "/usr/lib/python2.7/site-packages/paramiko/sftp_client.py", line 390, in rmdir
self._request(CMD_RMDIR, path)
File "/usr/lib/python2.7/site-packages/paramiko/sftp_client.py", line 729, in _request
return self._read_response(num)
File "/usr/lib/python2.7/site-packages/paramiko/sftp_client.py", line 776, in _read_response
self._convert_status(msg)
File "/usr/lib/python2.7/site-packages/paramiko/sftp_client.py", line 806, in _convert_status
raise IOError(text)
IOError: Failure
This is not the case when I'm using sftp.remove(path) for a single file. But sftp.rmdir causing IOError
The syntax is from the documentation.
The error is because the destination directory has got files inside it.
Try recurssive delete instead.. See below..
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(host,username=username,password=password)
filepath="/root/test_folder"
cmd = "rm -rf " + filepath
stdin, stdout, stderr = ssh.exec_command(cmd)
while not stdout.channel.exit_status_ready():
time.sleep(5)
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 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.