我有一个要求,我需要执行以下操作
我需要 ssh 到 Linux 盒子,运行命令,获取输出,然后我需要做一些操作。
这可以通过 python 子进程模块实现吗?
基本上,我需要一个 .py 代码,在其中我将提供用于连接到 Linux 盒子的 IP 地址、用户名和密码,并运行命令并获取输出。
也可以通过 Python 中可用的任何其他模块实现这一点。
欢迎提出建议。
最佳答案
您的问题被标记为“paramiko”,那么您为什么不直接使用它呢?
I need to ssh to a linux box , run a command , get the output back and i need to do some manipulations.
ssh 到 Linux 盒子(或任何其他 ssh 服务器):
>>> import paramiko
>>> ssh=paramiko.SSHClient()
>>> ssh.load_system_host_keys()
>>> ssh.connect(hostname='localhost', username='haiprasan86', password='secret')
>>> print ssh
<paramiko.SSHClient object at 0xdf2590>
运行命令:
>>> _, out, err = ssh.exec_command('ls -l /etc/passwd')
>>> # block until remote command completes
>>> status = out.channel.recv_exit_status()
>>> print status
0
获取输出:
>>> print out.readlines()
['-rw-r--r--. 1 root root 2351 Mar 27 10:57 /etc/passwd\n']
我不知道你想要做什么操作。
关于python - 使用子进程模块通过 SSH 连接 Linux 盒子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10815723/