python - 使用 Python 的 Paramiko 自动执行 ssh 连接和程序执行

标签 python ssh paramiko

我想使用 python 自动执行特定任务。
除其他事项外,此任务还包括通过 ssh 连接到远程服务器,以及运行可能会或可能不会要求用户输入的特定程序(称为 prog.out)。强>.
经过一些研究并权衡我的选择后,我决定使用 Python 的 Paramiko(考虑到以下情况,这可能是错误的......)。

让我们从 prog.out 不询问任何输入,而只是将一些信息打印到控制台的简单可能性开始:

int main(int argc, char* argv[]) {

        printf("Hey there, fella\n");
        printf("How are you this morning?\n");
        printf("See ya...\n");

        return 0;
}

编译为:prog.out,并位于server_name上,等待执行。
所以在这种情况下:

client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect("server_name")
sin, sout, serr = client.exec_command('./prog.out')

for line in sout.readlines():
    print(line, end = '')

将工作得很好,并且会打印出 prog.out 产生的任何内容。
但如果 prog.out 是:

int main(int argc, char* argv[]) {

        printf("Hey there, fella\n");
        printf("How are you this morning?\n");
        printf("please enter an integer...\n");
        int a;
        scanf("%d", &a);
        printf("you entered %d\n", a);
        printf("see ya...\n");

        return 0;
}

那么上面的Python代码将在sout.readlines()处阻塞(等待eof?)...
避免 sout.readlines() 中阻塞的方法是通过写入 prog.out 的标准输入管道来提供输入:

client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect("server_name")
sin, sout, serr = client.exec_command('./prog.out')

sin.write('55\n')

for line in sout.readlines():
    print(line, end = '')

但我无法提前知道 prog.out 是否需要用户输入...
我正在寻找一种可靠的方法来运行 prog.out 并让用户根据需要与其进行交互。 当 prog.out 需要输入时是否有一些指示?

编辑

好吧,我做了一些实验,发现只要 prog.out 还没有退出,任何从 channel 读取 read() 的尝试都会被阻塞,但是 prog.out 会被阻塞。 out 只要未提供输入就无法退出...
为什么我无法读取 prog.out 已发送的字节,即使它尚未完成?
我真的很想模拟用户,就好像他或她直接与 prog.out 交互一样...

最佳答案

有一个构建在 Paramiko 之上的库,它可能更适合您的需求。

我说的是python fabric (我与此无关)

Fabric is a Python (2.5-2.7) library and command-line tool for streamlining the use of SSH for application deployment or systems administration tasks.

It provides a basic suite of operations for executing local or remote shell commands (normally or via sudo) and uploading/downloading files, as well as auxiliary functionality such as prompting the running user for input, or aborting execution.

如果我正确理解了您的要求,您的代码可能如下所示。

from fabric.api import run

@task
def run_a_out()
    run('echo "some input for a.out" | ./a.out')

您将使用

执行远程程序
    fab --hosts=someserver run_a_out

如果您想动态控制传入 a.out 的内容,您可以向 run_a_out() 添加一个参数并从命令行传递它。

简而言之,Fabric 为 paramiko 提供了更高级别的 API,隐藏了大部分复杂性。

关于python - 使用 Python 的 Paramiko 自动执行 ssh 连接和程序执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37086065/

相关文章:

python - get_object_or_404 上的循环在条件失败后停止

linux - 如何从文件重定向密码请求?

python - 文件太大无法导入?

ssh - Gitlab 指纹已经被占用,部署 key 项目部署 key 指纹已经被占用

java - Java中通过SSH远程访问mySQL

python - 安装 Paramiko 错误

python - 在 Centos 中使用 pip 安装加密 python 库时出错

python - Paramiko的open_sftp()降落SSH服务器引发 “EOF during negotiation”异常

python - 递归类型注释

python - dict 和 collections.defaultdict 有什么区别?