常用脚本使用

while 使用

#!/bin/bash
rm -rf /home/log/log/*
for ip in `cat /home/log/log_week/warship2`
do
    ip=${ip//$'\r'}   # 获取的数据后隐藏的\r,进行处理
    echo "$ip"
    ssh_exit_code=0
    ssh -i /home/log/log_week/wrshg.pem -o "StrictHostKeyChecking no" root@$ip "python3 /root/log_week.py"
    ssh_exit_code=$?
    if [[ $ssh_exit_code != 0 ]]; then
        while [ $ssh_exit_code != 0 ]; do
            sleep 2
            ssh -i /home/log/log_week/wrshg.pem -o "StrictHostKeyChecking no" root@$ip "python3 /root/log_week.py"
            ssh_exit_code=$?
        done
    fi
done



for ip in `cat /home/log/log_week/warship2`
do
        ip=${ip//$'\r'}
        echo "$ip"
        name=`cat /home/log/log_week/warship1|grep $ip|awk '{print $2}'`
        ssh_exit_code=0
        scp -r -i /home/log/log_week/wrshg.pem -o "StrictHostKeyChecking no" root@$ip:/root/log /home/log/log/$name
        ssh_exit_code=$?
        if [[ $ssh_exit_code != 0 ]]; then
                while [ $ssh_exit_code != 0 ]; do
                        sleep 2
                        scp -r -i /home/log/log_week/wrshg.pem -o "StrictHostKeyChecking no" root@$ip:/root/log /home/log/log/$name
                        ssh_exit_code=$?
                done
        fi
done
cd /home/log/zip
name=`date '+%Y-%m-%d'`.zip
zip -r $name  /home/log/log

paramiko使用处理超时问题

def pok(ip):
    try:
        sys_ip = ip
        username = 'root'
        private_key_path = 'E:\\资料\\server.pem'
        private_key = paramiko.RSAKey.from_private_key_file(private_key_path)
        # 创建ssh客户端
        client = paramiko.SSHClient()
        # 第一次ssh远程时会提示输入yes或者no
        client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        # print('互信方式远程连接')
        client.connect(hostname=sys_ip, port=22, username=username, pkey=private_key, timeout=3000)

        command = "screen -ls"
        # print(command)
        # print(f"开始在远程服务器上执行指令:{cmmand}")
        # 执行查询命令
        stdin, stdout, stderr = client.exec_command(f"""{command}""", get_pty=True, timeout=3000)
        # 获取查询命令执c行结果,返回的数据是一个list
        result = stdout.read().decode('utf-8')
        client.close()
        # print(f"{sys_ip}执行结果:", result)
        result = filter(lambda line: "Detached" in line, result.split("\n"))
        return result
    except TimeoutError:
        print("链接超时")
        time.sleep(5)
        pok()

你可能感兴趣的:(python,linux,python,github,开发语言)