【问题标题】:Looping through ssh connections and directories循环通过 ssh 连接和目录
【发布时间】:2019-09-25 14:34:29
【问题描述】:

我正在使用 paramiko 远程访问各种主机。 我可以在 Putty shell 中运行类似的命令。

我正在编写一个希望能做到这一点的 python 脚本,但我正在努力使用 for 循环来

这是我的目录示例

   host01
      directory1
          file1
          file2
          file3
      directory2
          file1
          file2
          file3
   host02
      directory1
          file1
          file2
          file3
      directory2
          file1
          file2
          file3

import paramiko
ssh_client=paramiko.SSHClient()
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh_client.connect(hostname='host01',username='loginid',password='password')

stdin,stdout,stderr=ssh_client.exec_command('''
    cd ..
    cd user/ze/log
    cd *05-07-2019*
    grep -c 1= file1 
    ''')
for line in stdout.readlines():
    print (line.strip())
for line in stderr.readlines():
    print (line.strip())

等等……

最终我想为每个目录中的每个文件以某种模式grep。

我很难理解如何将变量用于上述内容。 任何帮助将不胜感激

【问题讨论】:

  • 如果您只需要grep,请仔细查看它的标志(特别是-R 和产生机器可读输出的标志)——这可能是一个更好的选择。跨度>

标签: python unix ssh putty paramiko


【解决方案1】:

我建议创建一个可以轻松传递值的方法。循环通过它取决于您如何存储 SSH 连接详细信息,我建议 listdict

您传递给 SSH 会话字符串的命令,以便您可以使用 string.format()。 python3的文档here

import paramiko


def ssh_grep(ssh_hostname, ssh_username, ssh_password, username, date, grep_filter)
    ssh_client=paramiko.SSHClient()
    ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh_client.connect(hostname=ssh_hostname,
                       username=ssh_username,
                       password=ssh_password)

    stdin, stdout, stderr=ssh_client.exec_command('''
        cd ..
        cd user/{username}/log
        cd *{date}*
        grep -c 1= {grep_filter}
        '''.format(username=username,
                   date=date,
                   grep_filter=grep_filter))
    for line in stdout.readlines():
        print (line.strip())
    for line in stderr.readlines():
        print (line.strip())


for item in ssh_list:
    ssh_grep(item['ssh_hostname'],
             item['ssh_username'],
             item['ssh_password'],
             item['username'],
             item['date'],
             item['grep_filter'])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-13
    相关资源
    最近更新 更多