# sshpy v1 by s0urd
# simple ssh client
# irc.gonullyourself.org 6667 #code
import paramiko
import os
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
privatekey = os.path.expanduser('/home/rabia/private')
mkey = paramiko.RSAKey.from_private_key_file(privatekey)
ssh.connect('78.46.172.47', port=22, username='s0urd', password=None, pkey=mkey)
while True:
pick = raw_input("sshpy: ")
stdin, stdout, stderr = ssh.exec_command(pick)
print stdout.readlines()
ssh.close()
When I try to run more then 1 command I get this error:
AttributeError: 'NoneType' object has no attribute 'open_session'
Looks like it's because at the end of the while loop you do ssh.close() (thus closing the session).
Related
Using paramiko to connect to remote host. How do i move across directories and perform unix operations? Sample code below
import paramiko
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('remote ip', username='username', password='password')
ftp = ssh.open_sftp()
ssh.exec_command('cd /folder1/folder2')
How do i perform operations like listing files in a directory, checking current working directory and perform other unix commands?
This way (example on ls command):
import paramiko
import sys
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('x.x.x.x', port=22, username='user', password='pass')
stdin, stdout, stderr = ssh.exec_command('ls')
# Wait for the command to terminate
while not stdout.channel.exit_status_ready():
# Only print data if there is data to read in the channel
if stdout.channel.recv_ready():
rl, wl, xl = select.select([stdout.channel], [], [], 0.0)
if len(rl) > 0:
# Print data from stdout
print stdout.channel.recv(1024),
ssh.close()
I can do ssh from one server to another using this:
# ssh root#1.2.4.148
The following code is doing the same in pythonic way:
import paraminko
#paramiko.util.log_to_file('ssh.log') # sets up logging
client = paramiko.SSHClient()
client.load_system_host_keys()
client.connect('1.2.4.148')
stdin, stdout, stderr = client.exec_command('ls -l')
But if I need to connect to third server from the second server, I can do this:
# ssh -t root#1.2.4.148 ssh root#1.2.4.149
How is this done in python?
My current server (250) has password less keys saved with 148 server for easy access. But connection to 149 from 148 will need password if that matters.
This python function will connect to middle_server first and then to last_server. It will execute the command "mycommand" on last_server and return it's output.
def myconnect():
middle_server='1.2.3.4'
middle_port=3232
middle_user='shantanu'
middle_key_filename='/root/.ssh/id_rsa.pub'
last_server='6.7.8.9'
last_port=1224
last_user='root'
last_password='xxxxx'
mycommand='pwd'
import paramiko
proxy_client = paramiko.SSHClient()
proxy_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
proxy_client.connect(middle_server, port=middle_port, username=middle_user, key_filename=middle_key_filename)
transport = proxy_client.get_transport()
dest_addr = (last_server, last_port)
local_addr = ('127.0.0.1', 1234)
channel = transport.open_channel("direct-tcpip", dest_addr, local_addr)
remote_client = paramiko.SSHClient()
remote_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
remote_client.connect('localhost', port=last_port, username=last_user, password=last_password, sock=channel)
(sshin1, sshout1, ssherr1) = remote_client.exec_command(mycommand)
print sshout1.read()
except:
print "error"
return 0
I have the following script to connect to an custom ssh shell.
When I execute the script it just hangs. It doesnt execute the command. I suspect problems with the shell because it does not have any prompt. Do you have any idea?
import sys
import os
import paramiko
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('10.115.130.22', username='admin', password='xxx', timeout = 30)
stdin, stdout, stderr = ssh.exec_command('xconfiguration SystemUnit Name: devicename')
print stdout.readlines()
ssh.close()`
I spent way too much time on this problem. I found that I needed to use the invoke_shell() to be able to get anything past the greeting banner on the Tandberg C/E series video endpoints. Here's my working code, FWIW:
import time
import paramiko
command = 'help'
host = 'x.x.x.x'
port = 22
user = 'admin'
passwd = 'TANDBERG'
def tbgShell(host,port,username,password,cmd):
"""send an arbitrary command to a Cisco/TBG gizmo's ssh and
get the result"""
transport = paramiko.Transport((host, port))
transport.connect(username = user, password = passwd)
chan = transport.open_channel("session")
chan.setblocking(0)
chan.invoke_shell()
out = ''
chan.send(cmd+'\n')
tCheck = 0
while not chan.recv_ready():
time.sleep(1)
tCheck+=1
if tCheck >= 6:
print 'time out'#TODO: add exeption here
return False
out = chan.recv(1024)
return out
output = tbgShell(host, port, user, passwd, command)
print output
This is a custom shell. It is a cisco ex90 video conferencing system.
But I tried different commands like xconfig which show you the config.
I'm fairly new to how Paramiko works, but my main objective is to be able to run automated commands over SSH using Python.
I have the following code and I am trying to run a simple ls command to start off with but for some odd reason the code seems to get stuck and no output or error messages are produced.
import sys
import paramiko as pm
sys.stderr = sys.__stderr__
import os
class AllowAllKeys(pm.MissingHostKeyPolicy):
def missing_host_key(self, client, hostname, key):
return
HOST = '192.168.31.1'
USER = 'admin'
PASSWORD = 'admin'
client = pm.SSHClient()
client.load_system_host_keys()
client.set_missing_host_key_policy(pm.AutoAddPolicy())
client.connect(HOST, username=USER, password=PASSWORD)
channel = client.invoke_shell()
stdin = channel.makefile('wb')
stdout = channel.makefile('rb')
stdin.write('''
ls
exit
''')
print stdout.read()
stdout.close()
stdin.close()
Any help would be much appreciated :)
I attempted the same route you were going, and didn't have much luck either. What I then opted for were the send() and recv() methods of the paramiko Channel class. Here is what I used:
>>> s = paramiko.SSHClient()
>>> s.load_system_host_keys()
>>> s.set_missing_host_key_policy(paramiko.AutoAddPolicy())
>>> s.connect(HOST,USER,PASS)
>>> c = s.invoke_shell()
>>> c.send('ls')
>>> c.recv(1024)
ls
bin etc usr home
proc var lib tmp
import paramiko
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
target_host = 'x.x.x.x'
target_port = 22
target_port = 22
pwd = ':)'
un = 'root'
ssh.connect( hostname = target_host , username = un, password = pwd )
stdin, stdout, stderr = ssh.exec_command('ls;exit')
#mrpopo,try this code which uses pecpect,
import pexpect
import pxssh
import time
import os
def tc(ipaddr,password):
try:
ss = pexpect.spawn(ipaddr)
ss.logfile = sys.stdout
print "SSH connecting"
print
except:
print "connection refused"
print
#sys.exit()
try:
ss.expect (':')
ss.sendline (password +"\n")
print "connected"
time.sleep(30)
ss.expect (">")
print "connection established"
print
except:
print "Permission denied, please try again."
print
sys.exit()
try:
ss.sendline ('ls\n')
ss.expect ('>')
tc("ssh admin#192.168.31.1,admin")
import paramiko
import os
def connection():
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
privatekey = os.path.expanduser('/home/rabia/private')
mkey = paramiko.RSAKey.from_private_key_file(privatekey)
ssh.connect('78.46.172.47', port=22, username='s0urd', password=None, pkey=mkey)
stdin, stdout, stderr = ssh.exec_command('ls')
print stdout.readlines()
connection()
How can I make it so that one thread is waiting for a user input and the other is doing the ssh connection?
If I'm understanding you correctly, then you should add something like this to your code:
import threading
_paramikoThread = threading.Thread(target=doParamikoConnection)
_paramikoThread.start()
# The following code is executed by parent thread.
_ans = ""
while _ans != "nay":
_ans = raw_input("Should I loop again? [yay/nay]")
# Now we've ended user I/O session, wait for connection to complete.
_paramikoThread.join()
# At this point we have data collected from user and connection being initialised.