基本paramiko exec_命令帮助

2024-05-15 12:46:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我是一个新的paramiko用户,在使用paramiko的远程服务器上运行命令有困难。我想导出一个路径并在后台运行一个名为tophat的程序。我可以用paramiko.sshclient()登录,但是我的exec_command代码没有结果。

stdin, stdout, sterr = ssh.exec_command('export PATH=$PATH:/proj/genome/programs
/tophat-1.3.0/bin:/proj/genome/programs/cufflinks-1.0.3/bin:/proj/genome/programs/
bowtie-0.12.7:/proj/genome/programs/samtools-0.1.16')

stdin, stdout, sterr = ssh.exec_command('nohup tophat -o /output/path/directory -I 
10000 -p 8 --microexon-search -r 50 /proj/genome/programs/bowtie-0.12.7/indexes
/ce9 /input/path/1 /input/path/2 &')

没有nohup.out文件,python只转到下一行,没有错误消息。我也尝试过不使用nohup,结果是一样的。我试着跟着this paramiko tutorial

我使用exec_command不正确吗?


Tags: pathparamikogenomebintophatstdinstdoutssh
3条回答

最好在运行命令之前加载bash_配置文件。否则可能会出现“找不到命令”异常。

例如,我编写命令command = 'mysqldump -uu -pp -h1.1.1.1 -P999 table > table.sql'是为了转储Mysql表

然后,在转储命令之前,我必须通过键入. ~/.profile; .~/.bash_profile;手动加载bash配置文件。

示例

my_command  = 'mysqldump -uu -pp -h1.1.1.1 -P999 table > table.sql;'

pre_command = """
. ~/.profile;
. ~/.bash_profile;
"""

command = pre_command + my_command

stdin, stdout, stderr = ssh.exec_command(command)

exec_command()是非阻塞的,它只是将命令发送到服务器,然后Python将运行以下代码。

我认为您应该等待命令执行结束,然后再做剩下的工作。

“time.sleep(10)”可能会有帮助,这需要“导入时间”。 一些示例显示,您可以从stdoutChannelFile对象中读取,或者简单地使用stdout.readlines(),它似乎可以读取服务器的所有响应,这可能会有所帮助。

您的代码,上面两行的exec_命令,实际上在不同的exec会话中运行。我不确定这对你的案子有没有影响。

我建议您查看demos文件夹中的demos,它们使用的是Channel类,该类有更好的API来为shell和exec执行阻塞/非阻塞发送。

我也遇到了同样的问题,在查看了this articlethis answer之后,我发现解决方案是调用通道的recv_exit_status()方法。这是我的代码:

import paramiko
import time

cli = paramiko.client.SSHClient()
cli.set_missing_host_key_policy(paramiko.client.AutoAddPolicy())
cli.connect(hostname="10.66.171.100", username="mapping")
stdin_, stdout_, stderr_ = cli.exec_command("ls -l ~")
# time.sleep(2)    # Previously, I had to sleep for some time.
stdout_.channel.recv_exit_status()
lines = stdout_.readlines()
for line in lines:
    print line

cli.close()

现在我的代码将被阻止,直到远程命令完成。此方法已解释为here,请注意警告。

相关问题 更多 >