使用popen在一个ssh会话中运行多个命令,并将输出保存在单独的文件中 [英] Run multiple commands in a single ssh session using popen and save the output in separate files

查看:281
本文介绍了使用popen在一个ssh会话中运行多个命令,并将输出保存在单独的文件中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在一个ssh会话中运行多个命令,并将每个命令的输出保存在不同的文件中.

I am trying to run several commands in a single ssh session and save the output of each command in a different file.

有效的代码(但它将所有输出保存在一个文件中)

The code that works (but it saves all the output in a single file)

conn = Popen(['ssh',host, "ls;uname -a;pwd"], stdin=PIPE, stdout = open ('/output.txt','w'))
mypassword = conn.communicate('password')

我正在尝试但不起作用的代码...

Codes that I am trying to work but not working...

cmd = ['ls', 'pwd', 'uname']
conn = Popen(['ssh',host, "{};{};{}".format(cmd[0],cmd[1],cmd[2])], stdin=PIPE, stdout = output.append('a')) 
mypassword = conn.communicate('password')

print (output)
length = range(len(output))
print length
for i in output:
open("$i",'w') 

cmd = ['ls', 'pwd', 'uname']
conn = Popen(['ssh',host, "{};{};{}".format(cmd[0],cmd[1],cmd[2])], stdin=PIPE, stdout = output())
mypassword = conn.communicate('password')

def output():

    for i in cmd:
        open(i,'w') 
    return

不确定执行此操作的最佳方法是什么.我应该将其保存在一个数组中,然后将每个项目保存在一个单独的文件中,还是应该调用一个可以执行此操作的函数? 请注意,我要运行的命令没有此处示例中给出的小输出(uname,pwd);它和tcpdump,lsof等一样大.

Not sure what is the best way of doing it. Should I save it in an array and then save each item in a separate file or should I call a function that will do it? NOTE that the commands I want to run do not have small output like given in examples here (uname, pwd); it is big as tcpdump, lsof etc.

推荐答案

SYS_STATS={"Number of CPU Cores":"cat /proc/cpuinfo|grep -c 'processor'\n",
               "CPU MHz":"cat /proc/cpuinfo|grep 'cpu MHz'|head -1|awk -F':' '{print $2}'\n",
               "Memory Total":"cat /proc/meminfo|grep 'MemTotal'|awk -F':' '{print $2}'|sed 's/ //g'|grep -o '[0-9]*'\n",
               "Swap Total":"cat /proc/meminfo|grep 'SwapTotal'|awk -F':' '{print $2}'|sed 's/ //g'|grep -o '[0-9]*'\n"}


def get_system_details(self,ipaddress,user,key):
        _OutPut={}
        values=[]
        sshProcess = subprocess.Popen(['ssh','-T','-o StrictHostKeyChecking=no','-i','%s' % key,'%s@%s'%(user,ipaddress),"sudo","su"],
                                      stdin=subprocess.PIPE, stdout = subprocess.PIPE, universal_newlines=True,bufsize=0)

        for element in self.SYS_STATS1:
            sshProcess.stdin.write("echo END\n")
            sshProcess.stdin.write(element)

        sshProcess.stdin.close()
        for element in sshProcess.stdout:
            if element.rstrip('\n')!="END":
                values.append(element.rstrip('\n'))
        mapObj={k: v for k, v in zip(self.SYS_STATS_KEYS, values)}

        return mapObj

这篇关于使用popen在一个ssh会话中运行多个命令,并将输出保存在单独的文件中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆