简体   繁体   English

使用python登录到Linux计算机并打开2个终端并执行命令

[英]Using python to login to a linux machine and open 2 terminals and execute commands

I need to ssh into linux pc and open 2 terminals and execute 2 commands- 1 command in terminal 1 and another command in terminal 2. How should I do this using python scripting? 我需要ssh进入linux pc并打开2个终端并执行2个命令-在终端1中执行1个命令,在终端2中执行另一个命令。如何使用python脚本执行此操作?

TIA TIA

Use paramiko module: Create connection using paramiko.SSHClient ; 使用paramiko模块:使用paramiko.SSHClient创建连接; then run twice its exec_command method (both will run in different channels <=> two terminals ; you can interact with them in any order you want (write to stdin handles, read from stdout and stderr handles) 然后运行它的exec_command方法两次(都将在两个终端的不同通道<=>中运行;您可以按所需的任何顺序与它们进行交互(写入stdin句柄,从stdout和stderr句柄读取)

EDIT: for long running commands may be better to use invoke_shell method instead of exec_command 编辑:对于长时间运行的命令,最好使用invoke_shell方法而不是exec_command

import paramiko
client = paramiko.SSHClient()
client.load_system_host_keys()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect('1.2.3.4', username='user', password='passwd')

shell1 = client.invoke_shell()
shell1.write('cmd\n')

shell2 = client.invoke_shell()
shell2.write('cmd\n')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM