Python paramiko执行远程Shell脚本并以字符串格式获取输出

问题描述

这是示例脚本。我想用本地计算机上的Python ./script.sh执行位于远程计算机10.0.0.1上的Bash Shell ./script.py

./ script.sh(远程Shell脚本)

echo line 1
echo line 2

./ script.py(本地Python脚本)

from paramiko import SSHClient

hostname = '10.0.0.1'
username = 'u'
password = 'p'

client = SSHClient()
client.load_system_host_keys()
client.connect(hostname,username=username,password=password)

stdin,stdout,stderr = client.exec_command('./script.sh')

我注意到这3种方法会产生不同类型的输出

stdout.read()-字节

>>> stdin,stderr = client.exec_command('./script.sh')
>>> stdout.read()
b'line 1\nline 2\n'
>>> 

stdout.readline()-字符串

>>> stdin,stderr = client.exec_command('./script.sh')
>>> stdout.readline()
'line 1\n'
>>> 

stdout.readlines()-列表

>>> stdin,stderr = client.exec_command('./script.sh')
>>> stdout.readlines()
['line 1\n','line 2\n']
>>> 

即使我想使用远程计算机中的Python执行该脚本,我也希望获得类似的shell脚本输出

remote@computer:~$ ./script.sh 
line 1
line 2
remote@computer:~$ 

所需的输出

wolf@linux:~$ python script.py
line 1
line 2
wolf@linux:~$ 

请让我知道获得此输出的最佳方法

解决方法

您可能可以:

comment.objects.filter(post=pk)

...并在最后扔出一些东西来检查退出代码。

,

bytes转换为string

bytes2string = stdout.read().decode('utf-8')

例如

>>> bytes2string
'line 1\nline 2\n'
>>> 

使用分割线将string转换为list格式,以便我们稍后进行迭代

j = bytes2string.splitlines()

例如

>>> j
['line 1','line 2']
>>> 

使用for循环逐行打印出列表中的所有元素

for i in j:
    print(i)

例如

>>> for i in j:
...     print(i)
... 
line 1
line 2
>>>