使用sshpass执行远程命令和拷贝

使用sshpass执行远程命令和拷贝

系统Ubuntu 16.04
安装sshpass: sudo apt-get install sshpass

import subprocess


def get_command_result(command):
    """
    用来执行终端命令,并拿到返回结果
    :param command: 需要执行的命令
    :return:
    """
    output_stdout, output_error = "None1", "None2"
    try:
        popen = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True, bufsize=4096)
        output_stdout, output_error = popen.communicate()
    except Exception as e:
        print("exec command error: {}".format(e))
    finally:
        return output_stdout.decode(), output_error.decode()

password = "password"
test_ip = "username@ip"

# # 远程登录 并输出所在路径
ssh_pwd_command = "sshpass -p {0} ssh {1} pwd".format(password, test_ip)
print(get_command_result(ssh_pwd_command))

# 远程登录 读取文件中的密码 -f
password_file = "/home/test/demo/ssh_demo/tester_password"
ssh_file_pw_command = "sshpass -f {0} ssh {1} pwd".format(password_file, test_ip)
print(get_command_result(ssh_file_pw_command))

# 在ubuntu系统里面安装ssh服务之后 ls ~/.ssh  id_dsa私钥 id_dsa.pub公钥
# 在首次连接服务器时,会弹出公钥确认的提示
# -o StrictHostKeyChecking=no 表示远程连接时不提示是否输入yes/no
ssh_check_command = "sshpass -p {0} ssh -o StrictHostKeyChecking=no {1} pwd".format(password, test_ip)
print(get_command_result(ssh_check_command))

# 防止远程主机公钥改变导致 SSH 连接失败
# -o UserKnownHostsFile=/dev/null known_hosts指向其他文件
ssh_check_command = "sshpass -p {0} ssh -o UserKnownHostsFile=/dev/null {1} pwd".format(password, test_ip)
print(get_command_result(ssh_check_command))

# -o StrictHostKeyChecking=no和-o UserKnownHostsFile=/dev/null结合就可以跳过所有的验证
ssh_check_command = "sshpass -p {0} ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null {1} pwd".format(password, test_ip)
print(get_command_result(ssh_check_command))

未完待续

附: Python远程拷贝文件夹/文件

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值