Python调用shell的几种方式

本文介绍了几种通过Python实现远程执行命令的方法,包括使用subprocess、paramiko和commands模块。涵盖了本地命令执行、SSH连接及命令传递等场景。

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 commands
command = "nslookup " + node + " | grep Name -1 | grep Address| awk '{print $2}'"
result = commands.getoutput(command)
if (result == ""):
    return "unknown"

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、付费专栏及课程。

余额充值