2020-05-21 免密在远程服务器上执行命令

一.paramiko方式
前提:
1.安装过paramiko
pip install paramiko
2.生成了密钥对
ssh-keygen -t rsa -P '' -f ~/.ssh/id_rsa
3.将公钥拷至远程服务器(或直接复制粘贴到服务器~/.ssh/authorized_keys文件中)
ssh-copy-id -i ~/.ssh/id_rsa.pub ubuntu@123.206.26.82
# paramiko方式

import paramiko
port=22
keyPath='/home/ubuntu/.ssh/id_rsa'  #私钥路径,公钥已传至远程服务器,同时需保证私钥有可读权限
hostname="123.206.26.82"
username="ubuntu"

key=paramiko.RSAKey.from_private_key_file(keyPath) s=paramiko.SSHClient() s.load_system_host_keys() s.set_missing_host_key_policy(paramiko.AutoAddPolicy()) #不会提示knowhosts 找不到 s.connect(hostname,port,username,pkey=key) stdin,stdout,stderr=s.exec_command('ls >> ~/hh.txt') s.close() print (stdout.read()) print (stderr.read())

 二.ansible 方式

前提:

1.安装了ansible

sudo apt install ansible

2.配置了密钥对并已将公钥上传至远程服务器

 同上.

3.将远程服务器的ip已经添加到ansible 的hosts文件中

echo "123.203.26.82" >> /etc/ansible/hosts
# ansible 方式
ansible -u ubuntu 123.206.26.82 -m shell -a "ls >> ~/hh.txt"

猜你喜欢

转载自www.cnblogs.com/cxl-blog/p/12934473.html
今日推荐