遍历ssh连接和目录

时间:2019-05-07 21:51:00

标签: python unix ssh putty paramiko

我正在使用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())

以此类推。

最终,我想对每个目录中的每个文件进行某种格式的重复设置。

我正在努力了解如何处理上述变量。 任何帮助将不胜感激

1 个答案:

答案 0 :(得分:0)

我建议创建一种可以轻松将值传递给的方法。循环浏览取决于您存储SSH连接详细信息的方式,我建议在list中的dict

您传递给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'])