Programing

스크립트를 사용하여 SSH 비밀번호 자동 입력

crosscheck 2020. 5. 26. 19:40
반응형

스크립트를 사용하여 SSH 비밀번호 자동 입력


OpenSSH ssh클라이언트에 자동으로 비밀번호를 입력하는 스크립트를 작성해야합니다 .

myname@somehost비밀번호 사용하여 SSH로 연결해야한다고 가정 해 봅시다 a1234b.

이미 시도했습니다 ...

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

...하지만 작동하지 않습니다.

이 기능을 스크립트로 가져 오려면 어떻게해야합니까?


먼저 sshpass 를 설치해야합니다 .

  • 우분투 / 데비안 : apt-get install sshpass
  • 페도라 / 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

노트:

  • sshpass-f플래그가 전달 될 때 파일에서 암호를 읽을 수도 있습니다 .
    • 를 사용 -f하면 ps명령이 실행될 때 비밀번호가 표시되지 않습니다 .
    • 비밀번호가 저장된 파일에는 보안 권한이 있어야합니다.

몇 달 동안 질문에 대한 답을 찾은 후 마침내 더 나은 해결책을 찾았습니다. 간단한 스크립트 작성.

#!/usr/bin/expect

set timeout 20

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

eval spawn $cmd
expect "assword:"
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를 수행 할 수 있습니다.


expects 스크립트를 사용할 수 있습니다. 나는 꽤 오랫동안 글을 쓰지 않았지만 아래와 같이 보일 것입니다. 스크립트를 사용하여#!/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

변형 II

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

sshpass 더 나은 보안

나는이 스레드를 우연히 발견하여 보그 다운 된 서버로 ssh하는 방법을 찾았습니다 .SSH 연결 시도를 처리하는 데 1 분이 걸렸으며 암호를 입력하기 전에 시간이 초과되었습니다. 이 경우 프롬프트가 표시되면 즉시 비밀번호를 제공 할 수 있기를 원했습니다 .

서버가이 상태 인 경우 공개 키 로그인을 설정하기에는 너무 늦습니다.

sshpass구조에. 그러나 이것보다 더 좋은 방법이 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

예를 들어 랩톱을 닫아서 Wi-Fi가 중단 된 경우 자동 재 연결이 가능합니다.


# 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


I don't think I saw anyone suggest this and the OP just said "script" so...

I needed to solve the same problem and my most comfortable language is Python.

I used the paramiko library. Furthermore, I also needed to issue commands for which I would need escalated permissions using sudo. It turns out sudo can accept its password via stdin via the "-S" flag! See below:

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!")

Hope this helps someone. My use case was creating directories, sending and untarring files and starting programs on ~300 servers as a time. As such, automation was paramount. I tried sshpass, expect, and then came up with this.


I got this working as follows

.ssh/config was modified to eliminate the yes/no prompt - I'm behind a firewall so I'm not worried about spoofed ssh keys

host *
     StrictHostKeyChecking no

Create a response file for expect i.e. 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

Create your bash script and just call expect in the file

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

  expect answer.expect hadoopslave$i

  i=[$i + 1]
  sleep 5

done

Gets 128 hadoop datanodes refreshed with new config - assuming you are using a NFS mount for the hadoop/conf files

Hope this helps someone - I'm a Windows numpty and this took me about 5 hours to figure out!


This is how I log in to my servers.

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

    #!/bin/bash

    sshpass -p mypassword ssh root@$1

And therefore...

ssp server_ip

I have a better solution that inclueds login with your account than changing to root user. It is a bash script

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


The answer of @abbotto did not work for me, had to do some things differently:

  1. yum install sshpass changed to - rpm -ivh http://dl.fedoraproject.org/pub/epel/6/x86_64/sshpass-1.05-1.el6.x86_64.rpm
  2. the command to use sshpass changed to - sshpass -p "pass" ssh user@mysite -p 2122

I managed to get it working with that:

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

If you are doing this on a Windows system, you can use Plink (part of PuTTY).

plink your_username@yourhost -pw your_password

In the example bellow I'll write the solution that I used:

The scenario: I want to copy file from a server using sh script:

#!/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"

Use this script tossh within script, First argument is the hostname and second will be the password.

#!/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"

sudo ssh username@server_ip_address -p port_number

press key enter and then enter your system's password and then finally enter your server password


To connect remote machine through shell scripts , use below command:

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

where IPADDRESS, USERNAME and PASSWORD are input values which need to provide in script, or if we want to provide in runtime use "read" command.

참고URL : https://stackoverflow.com/questions/12202587/automatically-enter-ssh-password-with-script

반응형