Authenticate with private key using Paramiko Transport (channel) - python

I'm trying to use Paramiko to open (and maintain) a channel so that I can issue a few commands; however, I'm unable to find an example using paramiko.Transport AND using a private key. I have been able to connect to my server and just run a command using the following code:
ssh = paramiko.SSHClient()
paramiko.util.log_to_file("support_scripts.log")
private_key = paramiko.RSAKey.from_private_key_file(rsa_private_key)
ssh.connect(server, username=user, password='', pkey=private_key)
ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command(cmd)
No problems there. From what I understand, that doesn't create an "interactive session", meaning I can't issue cd /home/my_user/my_scripts and then issue another command like python script_in_my_scripts_folder.py. Therefore, I'm trying to use the Paramiko Transport object which can help me maintain an interactive session. Searching high and low, none of the examples I've found work for me. Right now, the following code returns "SSHException: Channel is not open" on line 204, which is the exec_command below:
PRIVATEKEY = '/home/my_user/.ssh/id_rsa'
user = 'harperville'
server = '10.0.10.10'
port = 22
paramiko.util.log_to_file("support_scripts.log")
trans = paramiko.Transport((server,port))
rsa_key = paramiko.RSAKey.from_private_key_file(PRIVATEKEY)
trans.connect(username=user, pkey=rsa_key)
session = trans.open_channel("session")
session.exec_command('cd /home/harperville/my_scripts/')
I understand the gist of what it's telling me but I can't find or understand the documentation to help me get past this problem.
Thanks in advance.

I have found the issue with help from this site: http://j2labs.tumblr.com/post/4477180133/ssh-with-pythons-paramiko
If I change:
session = trans.open_channel("session")
to:
session = trans.open_session()
Then, I am allowed to run a command using:
session.exec_command('cd /home/harperville/my_scripts/')

Related

Fetch prelogin banner from SSH server using Paramiko without authenticating

I am trying to fetch banner from sever using below code. But the result always says "None", even thought banner exists. I have tried with Python 2 and 3, Paramiko 2.4 and 2.7.0, same result as "None".
Can anyone correct/help me?
The code is based on:
Is there a way using paramiko and python to get the banner of the ssh server you connected to?
The banner is configured in sshd_config using Banner directive.
# !/usr/bin/python
import paramiko
def grab_banner(ip_address, port):
client = paramiko.SSHClient()
client.load_system_host_keys()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
client.connect(ip_address, port=port, username='username',
password='bad-password-on-purpose')
except:
return client._transport.get_banner()
if __name__ == '__main__':
print grab_banner('192.168.1.26', 22)
Thanks
In general I believe that your code should work. But as after failed password authentication, Paramiko tries in vain various other authentication methods, the further attempts will discard the banner (it looks like a bug in Paramiko to me).
Prevent that by setting look_for_keys and allow_agent in SSHClient.connect:
try:
client.connect(ip_address, port=port, username='username',
password='bad-password-on-purpose',
look_for_keys=False, allow_agent=False)
except:
return client._transport.get_banner()
Here is a fix for Paramiko that allows retrieving the banner without the above workaround:
https://github.com/paramiko/paramiko/pull/438

How to keep paramiko ssh session open after loggin in using python?

I am trying to ssh to a test cisco router in a test environment using python paramiko, and run cisco commands in that test router.
Everything works great except for 1 small detail.
After running the script I want the ssh session to remain open. (so I can run other commands manually).
I want to keep the ssh session open until I type "exit"
I found another link with a similar issue but I cant understand the solution.
(See here Python ssh - keep connection open after script terminates)
I would appreciate if someone can help me out here
My code
import paramiko
import time
def ssh_session(ip):
try:
session = paramiko.SSHClient() #Open the session
session.set_missing_host_key_policy(paramiko.AutoAddPolicy())
session.connect(ip, username = "ciscouser1", password = "password")
connection = session.invoke_shell()
####Running Cisco IOS commands###
connection.send("enable\n")
connection.send("password1") #sending
connection.send("\n")
connection.send("configure terminal\n\n")
time.sleep(1)
connection.send("do show ip int brief\n")
time.sleep(1)
except paramiko.AuthenticationException:
print "wrong credentials"
ssh_session("10.10.10.1")
The session timeout would be controlled by the SSH server. To the best of my knowledge, the only way to keep your session alive on the client side is to not be inactive, which can be accomplished by sending null packets. As to how to do this specifically with paramiko I am not certain. Perhaps you could send some kind of dummy command (or maybe even an empty string?) every so often?

How to SSH from one system to another using python

I am trying to perform SSH from one system to another using paramiko in python
import paramiko
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(
paramiko.AutoAddPolicy())
ssh.connect('127.0.0.1', username='jesse',
password='lol')
using this reference (http://jessenoller.com/blog/2009/02/05/ssh-programming-with-paramiko-completely-different )
This is the case when we know the password of the system you want to log-in BUT
if i want to login to a system where my public-key is copied and i dont know the password. Is there a way to do this
Thanks in advance
SSHClient.connect accepts a kwarg key_filename, which is a path to the local private key file (or files, if given a list of paths). See the docs.
key_filename (str) – the filename, or list of filenames, of optional private key(s) to try for authentication
Usage:
ssh.connect('<hostname>', username='<username>', key_filename='<path/to/openssh-private-key-file>')
This code should work:
import paramiko
host = "<your-host>"
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(host, username='<your-username>', key_filename="/path/to/.ssh/id_rsa" , port=22)
# Just to test a command
stdin, stdout, stderr = client.exec_command('ls')
for line in stdout.readlines():
print line
client.close()
Here is the documentation of SSHClient.connect()
EDIT : /path/to/.ssh/id_rsa is your private key!
Adding the key to a configured SSH agent would make paramiko use it automatically with no changes to your code.
ssh-add <your private key>
Your code will work as is. Alternatively, the private key can be provided programmatically with
key = paramiko.RSAKey.from_private_key_file(<filename>)
SSHClient.connect(pkey=key)

Cannot connect to ssh via python

so I just setted up a fresh new raspberry pi and I want it to communicate with python using ssh from my computer to my ssh server, the pi.. I first try to connect using putty and it work, I could execute all the commands I wanted, then I tried using librarys such as Paramiko, Spur and they didn't work.
Spur code:
import spur
shell = spur.SshShell("192.168.1.114", "pi", "raspberry")
result = shell.run("ls")
print result
Paramiko code:
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(host, username, password)
Here's the error code:
spur.ssh.ConnectionError: Error creating SSH connection
Original error: Server '192.168.1.114' not found in known_hosts
This is the error with spur but it pretty much said the same thing with paramiko.
Thanks in advance :)
You need to accept the host key, similarly to what is shown here
import spur
shell = spur.SshShell("192.168.1.114",
"pi",
"raspberry",
missing_host_key=spur.ssh.MissingHostKey.accept)
result = shell.run("ls")
print result
EDIT: More useful link (spur documentation)

How to use Pageant with Paramiko on Windows?

I know that Paramiko supports Pageant under Windows, but it doesn't work by default.
I am looking for an example of connecting using the key that is loaded in Pageant.
This is what I am using to connect and do an automated login using Pageant to store my key, and connecting to it from within my Python script. It counts on Pageant already being loaded, (and I haven't found a good reliable way to launch it and load the key (prompt for key password)) but the below works for now.
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
host = 'somehost.com'
port = 22
ssh.connect(host, port=port, username='user', allow_agent=True)
stdin,stdout,stderr = ssh.exec_command("ps -ef")
print stdout.read()
print stderr.read()

Categories

Resources