ssh 免密码登录,脚本

ssh 免密码登录,脚本
ssh 免密码登录,需要使用公私钥来认证@import url(http://www.blogjava.net/CuteSoft_Client/CuteEditor/Load.ashx?type=style&file=SyntaxHighlighter.css);@import url(/css/cuteeditor.css);

首先通过 ssh-keygen 生成一对公私钥,默认在 ~/.ssh/id_rsa.pub 和 ~/.ssh/id_rsa,前面的是公钥。
认证就是要把这个文件加到远程用户目录 ~/.ssh/authorized_keys 文件中,而且这个文件的权限不能被其它人访问。

下面的脚本能够自动把这个文件放到远程,方法是 ./addpk ip username password

#!//usr/bin/expect
set host [lrange $argv 0 0]
set user [lrange $argv 1 1]
set passwd [lrange $argv 2 2]
proc ssh {cmd} {
    global user host passwd
    spawn ssh $user@$host "$cmd"
    expect {
        "*conne*" {
            send "yes\n"
            expect "*password*"
            send "$passwd\n"
            expect eof
        }
        "*password*" {
            send "$passwd\n"
            expect eof
    }
    }
}
proc scp {src dest} {
    global user host passwd
    spawn scp $src $user@$host:$dest
    expect {
        "*conne*" {
            send "yes\n"
            expect "*password*"
            send "$passwd\n"
            expect eof
        }
        "*password*" {
            send "$passwd\n"
            expect eof
        }
    }
}
ssh "mkdir -p ~/.ssh"
scp "/home/user1/.ssh/id_rsa.pub" "~/.ssh/id_rsa.pub"
ssh "cat ~/.ssh/id_rsa.pub >> ~/.ssh/authorized_keys"
ssh "uniq ~/.ssh/authorized_keys > ~/.ssh/authorized_keys.tmp"
ssh "mv ~/.ssh/authorized_keys.tmp ~/.ssh/authorized_keys"
ssh "chmod 700 ~/.ssh"
ssh "chmod 600 ~/.ssh/*"

你可能感兴趣的:(ssh 免密码登录,脚本)