Ruby下有net/ssh方便连接SSH服务端,在Python下是否也存在类似的库呢?经过简单的搜索发现使用paramiko库的较多,于是乎尝试一下。
首先使用easy_install pycrypto安装pycrypto库作为ssh库的依赖,然后执行easy_install paramiko安装这个库。
编写如下代码进行测试:
import paramiko
if __name__ == "__main__":
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect('127.0.0.1',22,username='root',password='root',timeout=4)
stdin,stdout,stderr = client.exec_command('ps aux')
for std in stdout.readlines():
print std,
client.close()
执行后输出如下:
USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
root 1 0.0 0.0 3440 552 ? S Feb19 0:01 init [3]
root 2 0.0 0.0 0 0 ? S Feb19 0:00 [migration/0]
root 3 0.0 0.0 0 0 ? SN Feb19 0:00 [ksoftirqd/0]
root 4 0.0 0.0 0 0 ? S Feb19 0:00 [migration/1]
表示执行成功!