新系统添加sshkey
Posted freshmans
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了新系统添加sshkey相关的知识,希望对你有一定的参考价值。
Ansible密码认证
//配置Inventory [db] 10.10.10.12 10.10.10.162 [db:vars] #给db组下的主机设置变量 ansible_ssh_user="root" ansible_ssh_pass=‘123456‘ //调用ansible的authorized_key模块(可参考https://www.cnblogs.com/FRESHMANS/p/8119224.html 里的authoirzed_key模块) ansible db -m authorized_key -a "user=root key={{ lookup(‘file‘, ‘/root/.ssh/id_rsa.pub‘) }} path=/root/.ssh/authorized_keys manage_dir=no"
//copy模块
ansible db -m copy -a "src=/root/.ssh/id_rsa.pub dest=/tmp/id_rsa.pub"
ansible db -m shell -a "cat /tmp/id_rsa.pub >> /root/.ssh/authorized_keys"
ssh-copy-id(需要手动输入密码)
ssh-keygen -t rsa ssh-copy-id 192.168.132.132 ssh-copy-id 192.168.132.133 ssh-copy-id 192.168.132.131 测试 ssh -i /root/.ssh/id_rsa [email protected]
Paramiko
略
Expect
安装
//安装依赖 wget http://nchc.dl.sourceforge.net/sourceforge/tcl/tcl8.4.11-src.tar.gz tar xfvz tcl8.4.11-src.tar.gz cd tcl8.4.11/unix ./configure --prefix=/usr/tcl --enable-shared make make install
//安装expect
wget https://jaist.dl.sourceforge.net/project/expect/Expect/5.45/expect5.45.tar.gz tar xzvf expect5.45.tar.gz cd expect5.45 ./configure --prefix=/usr/expect --with-tcl=/usr/tcl/lib --with-tclinclude=../tcl8.4.11/generic make make install ln -s /usr/tcl/bin/expect /usr/expect/bin/expect
测试脚本
示例: #!/usr/bin/expect -f set ip [lindex $argv 0 ] #设置远程主机ip set USER [linux $argv 1] #设置要连接的远程主机用户信息 set password [lindex $argv 2 ] #设置远程主机密码信息
set CMD [linux argv 3] #设置要执行的命令 set timeout 10 spawn ssh [email protected]$ip $cmd #开启ssh连接并在远程主机执行命令 expect { "*yes/no" { send "yes "; exp_continue} "*password:" { send "$password " } } interact //检测基本登录并停留在远程主机shell cat ssh.exp #!/usr/bin/expect set timeout 30
spawn scp /root/.ssh/id_rsa.pub [email protected]:/root #直接往远程主机上拷贝文件,
spawn ssh-copy-id 10.10.10.162 #这里可以用ssh-copy-id做ssh免秘钥认证
spawn ssh -l root 10.10.10.11 #连接远程主机
expect "password:" send "[email protected] " interact 执行 expect ssh.exp //自定义连接主机 cat test_ssh.exp #!/usr/bin/expect -f set ip [lindex $argv 0 ] set password [lindex $argv 1 ] set timeout 10 spawn ssh [email protected]$ip expect { "*yes/no" { send "yes "; exp_continue} "*password:" { send "$password " } } interact expect test_ssh.exp ip password
其他示例
//更改密码 #!/bin/bash USER=mynameuser PASS=oldpassword NPASS=newpassword expect << EOF spawn passwd expect "Changing password for ${USER}." send "${PASS} " expect "Enter new UNIX password:" send "${NPASS} " expect "Retype new UNIX password:" send "${NPASS} " expect eof; EOF //文件拷贝 #!/usr/bin/expect set timeout 10 set host [lindex $argv 0] set username [lindex $argv 1] set password [lindex $argv 2] set src_file [lindex $argv 3] set dest_file [lindex $argv 4] spawn scp $src_file [email protected]$host:$dest_file expect { "(yes/no)?" { send "yes " expect "*assword:" { send "$password "} } "*assword:" { send "$password " } } expect "100%" expect eof
以上是关于新系统添加sshkey的主要内容,如果未能解决你的问题,请参考以下文章