簡體   English   中英

用腳本自動輸入SSH密碼

[英]Automatically enter SSH password with script

我需要創建一個腳本,自動將密碼輸入到 OpenSSH ssh客戶端。

假設我需要使用密碼a1234b將 SSH 放入myname@somehost

我已經試過了...

#~/bin/myssh.sh
ssh myname@somehost
a1234b

...但這不起作用。

我怎樣才能將此功能放入腳本中?

首先你需要安裝sshpass

  • Ubuntu/Debian: apt-get install sshpass
  • Fedora/CentOS: yum install sshpass
  • 拱門: pacman -S sshpass

例子:

sshpass -p "YOUR_PASSWORD" ssh -o StrictHostKeyChecking=no YOUR_USERNAME@SOME_SITE.COM

自定義端口示例:

sshpass -p "YOUR_PASSWORD" ssh -o StrictHostKeyChecking=no YOUR_USERNAME@SOME_SITE.COM:2400

筆記:

  • -f標志被傳遞時, sshpass還可以從文件中讀取密碼。
    • 如果執行ps命令,則使用-f可防止密碼可見。
    • 存儲密碼的文件應該具有安全權限。

在找了幾個月的問題答案后,我終於找到了一個更好的解決方案:編寫一個簡單的腳本。

#!/usr/bin/expect

set timeout 20

set cmd [lrange $argv 1 end]
set password [lindex $argv 0]

eval spawn $cmd
expect "password:"
send "$password\r";
interact

把它放到/usr/bin/exp ,所以你可以使用:

  • exp <password> ssh <anything>
  • exp <password> scp <anysrc> <anydst>

完畢!

使用公鑰認證: https : //help.ubuntu.com/community/SSH/OpenSSH/Keys

在源主機中只運行一次:

ssh-keygen -t rsa # ENTER to every field
ssh-copy-id myname@somehost

就是這樣,之后您就可以在沒有密碼的情況下執行 ssh。

您可以使用期望腳本。 我已經有一段時間沒有寫過一篇了,但它應該如下所示。 您需要使用#!/usr/bin/expect來引導腳本

#!/usr/bin/expect -f
spawn ssh HOSTNAME
expect "login:" 
send "username\r"
expect "Password:"
send "password\r"
interact

變體 I

sshpass -p PASSWORD ssh USER@SERVER

變體二

#!/usr/bin/expect -f
spawn ssh USERNAME@SERVER "touch /home/user/ssh_example"
expect "assword:"
send "PASSWORD\r"
interact

sshpass具有更好的安全性

我在尋找一種通過 ssh 進入陷入困境的服務器的方法時偶然發現了這個線程 - 處理 SSH 連接嘗試花了一分鍾多的時間,並且在我輸入密碼之前超時。 在這種情況下,我希望能夠在提示可用時立即提供我的密碼。

(如果不是很清楚:服務器處於這種狀態,設置公鑰登錄為時已晚。)

sshpass來救援。 但是,有比sshpass -p更好的方法來解決這個sshpass -p

我的實現直接跳到交互式密碼提示(沒有浪費時間查看是否可以進行公鑰交換),並且從不以純文本形式顯示密碼。

#!/bin/sh
# preempt-ssh.sh
# usage: same arguments that you'd pass to ssh normally
echo "You're going to run (with our additions) ssh $@"

# Read password interactively and save it to the environment
read -s -p "Password to use: " SSHPASS 
export SSHPASS

# have sshpass load the password from the environment, and skip public key auth
# all other args come directly from the input
sshpass -e ssh -o PreferredAuthentications=keyboard-interactive -o PubkeyAuthentication=no "$@"

# clear the exported variable containing the password
unset SSHPASS

sshpass + autossh

已經提到的一個不錯的獎金sshpass是,你可以用它autossh ,消除更加的互動效率低下。

sshpass -p mypassword autossh -M0 -t myusername@myserver.mydomain.com

這將允許自動重新連接,例如,您的 wifi 因關閉筆記本電腦而中斷。

我想我沒有看到有人提出這個建議,OP 只是說“腳本”所以......

我需要解決同樣的問題,而我最熟悉的語言是 Python。

我使用了 paramiko 庫。 此外,我還需要使用sudo發出需要升級權限的sudo 事實證明 sudo 可以通過標准輸入通過“-S”標志接受它的密碼! 見下文:

import paramiko

ssh_client = paramiko.SSHClient()

# To avoid an "unknown hosts" error. Solve this differently if you must...
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

# This mechanism uses a private key.
pkey = paramiko.RSAKey.from_private_key_file(PKEY_PATH)

# This mechanism uses a password.
# Get it from cli args or a file or hard code it, whatever works best for you
password = "password"

ssh_client.connect(hostname="my.host.name.com",
                       username="username",
                       # Uncomment one of the following...
                       # password=password
                       # pkey=pkey
                       )

# do something restricted
# If you don't need escalated permissions, omit everything before "mkdir"
command = "echo {} | sudo -S mkdir /var/log/test_dir 2>/dev/null".format(password)

# In order to inspect the exit code
# you need go under paramiko's hood a bit
# rather than just using "ssh_client.exec_command()"
chan = ssh_client.get_transport().open_session()
chan.exec_command(command)

exit_status = chan.recv_exit_status()

if exit_status != 0:
    stderr = chan.recv_stderr(5000)

# Note that sudo's "-S" flag will send the password prompt to stderr
# so you will see that string here too, as well as the actual error.
# It was because of this behavior that we needed access to the exit code
# to assert success.

    logger.error("Uh oh")
    logger.error(stderr)
else:
    logger.info("Successful!")

希望這可以幫助某人。 我的用例是在大約 300 台服務器上創建目錄、發送和解壓縮文件以及啟動程序。 因此,自動化至關重要。 我嘗試了sshpassexpect ,然后想出了這個。

這就是我登錄服務器的方式。

ssp <server_ip>
  • 別名 ssp='/home/myuser/Documents/ssh_script.sh'
  • cat /home/myuser/Documents/ssh_script.sh

#!/bin/bash

sshpass -p mypassword ssh root@$1

因此...

ssp server_ip
# create a file that echo's out your password .. you may need to get crazy with escape chars or for extra credit put ASCII in your password...
echo "echo YerPasswordhere" > /tmp/1
chmod 777 /tmp/1

# sets some vars for ssh to play nice with something to do with GUI but here we are using it to pass creds.
export SSH_ASKPASS="/tmp/1"
export DISPLAY=YOURDOINGITWRONG
setsid ssh root@owned.com -p 22

參考: https : //www.linkedin.com/pulse/youre-doing-wrong-ssh-plain-text-credentials-robert-mccurdy?trk=mp-reader-card

我正在使用以下解決方案,但為此您必須安裝sshpass如果尚未安裝,請使用sudo apt install sshpass

現在你可以這樣做,

sshpass -p *YourPassword* shh root@IP

您也可以創建一個 bash 別名,這樣您就不必一次又一次地運行整個命令。 按照以下步驟操作

cd ~

sudo nano .bash_profile

在文件末尾添加以下代碼

mymachine() { sshpass -p *YourPassword* shh root@IP }

source .bash_profile

現在只需從終端運行mymachine命令,您將在沒有密碼提示的情況下進入您的機器。

筆記:

  1. mymachine可以是您選擇的任何命令。
  2. 如果在此任務中安全性對您來說並不重要,而您只想自動化工作,則可以使用此方法。

這基本上是 abbotto 答案的擴展,還有一些額外的步驟(針對初學者)使從您的 linux 主機啟動服務器非常容易:

  1. 編寫一個簡單的 bash 腳本,例如:
#!/bin/bash

sshpass -p "YOUR_PASSWORD" ssh -o StrictHostKeyChecking=no YOUR_USERNAME@SOME_SITE.COM
  1. 保存文件,例如“startMyServer”,然后通過在終端中運行以下命令使文件可執行:
sudo chmod +x startMyServer
  1. 將文件移動到“PATH”變量中的文件夾(在終端中運行“echo $PATH”以查看這些文件夾)。 因此,例如將其移動到“/usr/bin/”。

瞧,現在您可以通過在終端中輸入“startMyServer”來進入您的服務器。

PS (1) 這不是很安全,查看 ssh 密鑰以獲得更好的安全性。

PS (2) SMshrimant 的答案非常相似,對某些人來說可能更優雅。 但我個人更喜歡在 bash 腳本中工作。

如果您在 Windows 系統上執行此操作,則可以使用 Plink(PuTTY 的一部分)。

plink your_username@yourhost -pw your_password

我按如下方式工作

.ssh/config 被修改以消除是/否提示 - 我在防火牆后面,所以我不擔心欺騙的 ssh 密鑰

host *
     StrictHostKeyChecking no

為expect ie answer.expect 創建一個響應文件

set timeout 20
set node [lindex $argv 0]
spawn ssh root@node service hadoop-hdfs-datanode restart

expect  "*?assword {
      send "password\r"   <- your password here.

interact

創建你的 bash 腳本並在文件中調用 expect

#!/bin/bash
i=1
while [$i -lt 129]    # a few nodes here

  expect answer.expect hadoopslave$i

  i=[$i + 1]
  sleep 5

done

使用新配置刷新 128 個 hadoop 數據節點 - 假設您對 hadoop/conf 文件使用 NFS 掛載

希望這對某人有所幫助 - 我是一個 Windows numpty,這花了我大約 5 個小時才弄清楚!

我有一個更好的解決方案,包括使用您的帳戶登錄,而不是更改為 root 用戶。 這是一個bash腳本

http://felipeferreira.net/index.php/2011/09/ssh-automatic-login/

@abbotto 的答案對我不起作用,必須做一些不同的事情:

  1. yum install sshpass 改為 - rpm -ivh http://dl.fedoraproject.org/pub/epel/6/x86_64/sshpass-1.05-1.el6.x86_64.rpm
  2. 使用 sshpass 的命令更改為 - sshpass -p "pass" ssh user@mysite -p 2122

我設法讓它與它一起工作:

SSH_ASKPASS="echo \"my-pass-here\""
ssh -tt remotehost -l myusername

在下面的示例中,我將編寫我使用的解決方案:

場景:我想使用 sh 腳本從服務器復制文件:

#!/usr/bin/expect
$PASSWORD=password
my_script=$(expect -c "spawn scp userName@server-name:path/file.txt /home/Amine/Bureau/trash/test/
expect \"password:\"
send \"$PASSWORD\r\"
expect \"#\"
send \"exit \r\"
")

echo "$my_script"

這有效:

#!/usr/bin/expect -f
spawn ssh USERNAME@SERVER "touch /home/user/ssh_example"
expect "assword:"
send "PASSWORD\r"
interact

但是,,, 如果您遇到如下錯誤:只需使用 expect 啟動腳本,而不是 bash,如下所示: expect myssh.sh而不是bash myssh.sh

/bin/myssh.sh: 2: spawn: not found /bin/myssh.sh: 3: expect: not found /bin/myssh.sh: 4: send: not found /bin/myssh.sh: 5: expect: not found /bin/myssh.sh: 6: send: not found

在腳本中使用此腳本 tossh,第一個參數是主機名,第二個參數是密碼。

#!/usr/bin/expect
set pass [lindex $argv 1]
set host [lindex $argv 0]
spawn ssh -t root@$host echo Hello
expect "*assword: " 
send "$pass\n";
interact"

要通過 shell 腳本連接遠程機器,請使用以下命令:

sshpass -p PASSWORD ssh -o StrictHostKeyChecking=no USERNAME@IPADDRESS

其中IPADDRESSUSERNAMEPASSWORD是需要在腳本中提供的輸入值,或者如果我們想在運行時提供使用“讀取”命令。

這在大多數情況下應該會有所幫助(您需要先安裝 sshpass!):

#!/usr/bin/bash
read -p 'Enter Your Username: ' UserName;
read -p 'Enter Your Password: ' Password;
read -p 'Enter Your Domain Name: ' Domain;

sshpass -p "$Password" ssh -o StrictHostKeyChecking=no $UserName@$Domain

在 linux/ubuntu 中

ssh username@server_ip_address -p port_number

按回車鍵,然后輸入您的服務器密碼

如果您不是 root 用戶,則在命令開頭添加sudo

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM