如何自動輸入密碼ssh連接到其他機器

想在shell腳本里ssh連接到另外一臺服務器後執行一些命令,但是不希望通過交互方式輸入登錄密碼。

主要的解決方法有三種:

1. 生成ssh公鑰,建立和對方機器的信任關係;

2. 使用expect腳本;

3. 使用sshpass。

這裏介紹一下sshpass相關內容

下載並安裝sshpass):

# tar zxvf sshpass-xxxx.tar.gz

# cd sshpass-xxxx

# ./configure

# make && make install


基本用法:sshpass -p [密碼] ssh [user]@[host]

免去第一次登錄機器時的確認提示(Are you sure you want to continue connecting (yes/no)):

sshpass -p [密碼] ssh [user]@[host] -o StrictHostKeyChecking=no

後面也可以跟上其他ssh命令,如scp等

例1,公司的一個環境,大部分機器的login密碼是"1root",少部分是"123qwe",新建一個hssh.sh文件,按如下修改,copy到/usr/bin/目錄下。

#!/bin/sh

#_main_
temp_file=/tmp/hssh.1
ip=192.168.$1
case "$1" in
 "204.188"|"207.31"|"205.199") password="123qwe";;
 *) password="1root"
esac

sshpass -p $password ssh root@$ip -o StrictHostKeyChecking=no 2>$temp_file
if [ $? != 0 ];then
    #for some reason,machine had reinstall, we need to delete that IP address in known_hosts file before ssh it.
    grep -q "REMOTE HOST IDENTIFICATION HAS CHANGED" $temp_file
    if [ $? = 0 ];then
       key_file=`grep "Offending key in" $temp_file | cut -d' ' -f 4 | cut -d ':' -f1 2>/dev/null`
       cat $key_file | grep -v "$ip" > $temp_file
       sudo cp -v $temp_file $key_file
       sshpass -p $password ssh root@$ip -o StrictHostKeyChecking=no 2>$temp_file
    fi
fi
那麼我們每次只要輸入hssh XXX.XXX 等就可以ssh到對應機器上了

發佈了36 篇原創文章 · 獲贊 12 · 訪問量 41萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章