使用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))
未完待续