Python调用shell的几种方式

本文介绍四种不同的方法来远程执行命令,包括使用subprocess模块直接调用命令、通过paramiko库建立SSH连接并执行命令、利用spur库简化SSH操作流程以及采用subprocess结合SSH进行命令传递。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.

cmd = "some unix command"
retcode = subprocess.call(cmd,shell=True)

2.

ssh = paramiko.SSHClient()
ssh.connect(server, username=username, password=password)
ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command(cmd_to_execute)

3.

import spur

shell = spur.SshShell(hostname="localhost", username="bob", password="password1")
result = shell.run(["echo", "-n", "hello"])
print result.output 
# prints hello

4.

sshProcess = subprocess.Popen(['ssh', <remote client>], ,stdin=subprocess.PIPE, stdout = subprocess.PIPE)
sshProcess.stdin.write("ls mydirectory\n")
sshProcess.stdin.write("echo END\n")
for line in stdout.readlines():
    if line == "END\n":
        break
    print(line)
sshProcess.stdin.write("uptime\n")
sshProcess.stdin.write("echo END\n")
for line in stdout.readlines():
    if line == "END\n":
        break
    print(line)

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值