S28.shell脚本每日一练

55.expect 位置参数实现ssh自动登录

[root@rocky8 ~]# vim expect3
#!/usr/bin/expect
set ip [lindex $argv 0]
set user [lindex $argv 1]
set password [lindex $argv 2]
set timeout 10
spawn ssh $user@$ip
expect {
    
    
    "yes/no" {
    
     send "yes\n";exp_continue }
    "password" {
    
     send "$password\n" }
}
interact

[root@rocky8 ~]# chmod +x expect3

[root@rocky8 ~]# ./expect3 172.31.0.6 root 123456
spawn ssh [email protected]
[email protected]'s password: 
Last login: Fri Oct 22 14:02:02 2021 from 172.31.0.1
[root@centos6 ~]# exit
logout
Connection to 172.31.0.6 closed.

56.shell脚本调用 expect

[root@rocky8 ~]# vim expect4.sh
#!/bin/bash
#
#**********************************************************************************************
#Author:        Raymond
#QQ:            88563128
#Date:          2021-10-22
#FileName:      expect4.sh
#URL:           raymond.blog.csdn.net
#Description:   The test script
#Copyright (C): 2021 All rights reserved
#*********************************************************************************************
ip=$1
user=$2
password=$3
expect <<EOF
set timeout 20
spawn ssh $user@$ip
expect {
    
    
    "yes/no" {
    
     send "yes\n";exp_continue }
    "password" {
    
     send "$password\n" }     
}
expect "]#" {
    
     send "useradd hehe\n" }
expect "]#" {
    
     send "echo 123456|passwd --stdin hehe\n" }
expect "]#" {
    
     send "exit\n" }

[root@rocky8 ~]# chmod +x expect1.sh 
[root@rocky8 ~]# ./expect1.sh 172.31.0.7 root 123456
./expect1.sh: line 24: warning: here-document at line 15 delimited by end-of-file (wanted `EOF')
spawn ssh [email protected]
[email protected]'s password: 
Last login: Fri Oct 22 15:46:24 2021 from 172.31.1.8
[root@centos7 ~]# useradd hehe
[root@centos7 ~]# echo 123456|passwd --stdin hehe
Changing password for user hehe.
passwd: all authentication tokens updated successfully.
[root@centos7 ~]# [root@rocky8 ~]# 

[root@centos7 ~]# id hehe
uid=1001(hehe) gid=1001(hehe) groups=1001(hehe)

猜你喜欢

转载自blog.csdn.net/qq_25599925/article/details/126772775