在centOS环境下,进行操作的步骤:
1.生成ssh免登陆密钥
cd ~,进入到我的home目录
cd .ssh/
ssh-keygen -t rsa (四个回车)
执行完这个命令后,会生成两个文件id_rsa(私钥)、id_rsa.pub(公钥)
将公钥拷贝到要免登陆的机器上
cat ~/.ssh/id_rsa.pub >> ~/.ssh/authorized_keys
或
ssh-copy-id -i localhost
把生成的id_rsa保存在test.py同目录下
1.fab 命令使用:
# test.py
# coding:utf-8 #!/user/bin/python ''' Created on 2017年3月22日 @author: yizhiwu 自动化脚本 ''' from fabric.api import settings, run, cd env.hosts = ['xxx.xxx.xxx.xxx'] env.user = 'root' env.key_filename = "./id_rsa" def ls_path(): print(green("I'm local /home/apps/")) with cd('/home'): run('ls -l')
# fab ls_path
[111.230.177.230] run: ls -l
[111.230.177.230] out: total 8
[111.230.177.230] out: drwx------ 7 appuser appuser 4096 Mar 30 15:06 appuser
[111.230.177.230] out: drwxr-xr-x 14 root root 4096 Mar 30 15:24 myfile
[111.230.177.230] out:
Done.
Disconnecting from 111.230.177.230... done.
2.fab 函数命令使用:
# test.py
# coding:utf-8 # !/user/bin/python ''' Created on 2017年3月22日 @author: yizhiwu 自动化脚本 ''' from fabric.api import settings, run, cd host = 'xxx.xxx.xxx.xxx' user = 'root' key_filename = "./id_rsa" def ls_path(): with settings(host_string=host, key_filename=key_filename, user=user, warn_only=True): with cd('/home'): run('ls -l') if __name__ == '__main__': ls_path()
# python test.py
输出:
[111.230.177.230] run: ls -l
[111.230.177.230] out: total 8
[111.230.177.230] out: drwx------ 7 appuser appuser 4096 Mar 30 15:06 appuser
[111.230.177.230] out: drwxr-xr-x 14 root root 4096 Mar 30 15:24 myfile
[111.230.177.230] out:
备注:
root用户和非root用户共用id_rsa:
非root用户执行
# ssh-keygen -t rsa
记下
Your identification has been saved in /home/appuser/.ssh/id_rsa.
Your public key has been saved in /home/appuser/.ssh/id_rsa.pub.
执行:
# cd /home/appuser/.ssh
# touch authorized_keys
# chmod 600 authorized_keys
把需要授权的id_rsa和id_rsa.pub私钥和公钥复制进/home/appuser/.ssh
写入授权
# cat /home/appuser/.ssh/id_rsa.pub >> /home/appuser/.ssh/authorized_keys