法1:使用 exec.command(),此方法不适合用 sudu su不输入密码的状况
#!/usr/bin/env python
import paramiko
hostname=‘172.16.88.117‘
username=‘liuqian‘
pk_path=‘/home/liuqian/.ssh/id_rsa‘
try:
key=paramiko.RSAKey.from_private_key_file(pk_path)
except paramiko.PasswordRequiredException:
password = getpass.getpass(‘RSA key password:
‘)
key =
paramiko.RSAKey.from_private_key_file(pk_path, password)
#
需要口令的私钥
ssh=paramiko.SSHClient()
ssh.load_system_host_keys()
ssh.connect(hostname=hostname, username=username,
pkey=key)
stdin, stdout, stderr=ssh.exec_command(‘cd /var/log;ls‘)
# 下面的方法适合使用密码登陆的状况
# ssh.connect(hostname=hostname,
username=username, password=‘123456’)
# stdin, stdout,
stderr=ssh.exec_command(‘sudo su‘)
# stdin.write(‘123456‘)
# stdin.flush()
print stdout.readlines()
print stderr.readlines()
ssh.close()
法2:使用 send()
#!/usr/bin/env python
import paramiko
import time
import socket
ip=‘172.16.88.117‘
username=‘liuqian‘
pk_path=‘/home/liuqian/.ssh/id_rsa‘
cmds=[‘sudo su\n‘, ‘cd /var/log\n‘, ‘ls\n‘]
try:
key=paramiko.RSAKey.from_private_key_file(pk_path)
except paramiko.PasswordRequiredException:
password = getpass.getpass(‘RSA key password:
‘)
key =
paramiko.RSAKey.from_private_key_file(pk_path, password)
s=paramiko.SSHClient()
s.load_system_host_keys()
try:
s.connect(hostname=ip,username=username,pkey=key,timeout=5)
except socket.timeout as e:
sys.exit(1)
ssh=s.invoke_shell()
for cmd in cmds:
time.sleep(1)
ssh.send(cmd)
out = ssh.recv(1024)
print out
ssh.close()