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")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.