shell自动化输入

news/2024/7/24 4:51:05 标签: expect, 自动输入, 引号, shell

shell自动化输入的三种方式:

前两种的前提是指令需要有参数来指定密码输入方式,具体使用可参考博客:

https://blog.csdn.net/zhangjikuan/article/details/51105166

下面讲一下expect方式的使用

当不想要手动输入时(如:密码),可使用expect来实现脚本自动输入

安装:

shell">yum install expect -y

shell脚本内使用:

shell">if [[ "x${use_v2v_local_cmd}" == "xtrue" ]]; then
    if [[ "x${password_file}" != "x" ]]; then
        passwd=`cat ${password_file}`
        expect <<-EOF
        set timeout -1

        spawn ${v2v_local_cmd}
        expect {
            "*password*" {
                send "${passwd}\r"
                exp_continue
            }
            "*error*" {
                exit 1
            }
        }
EOF
    else
        eval ${v2v_local_cmd}
    fi
fi

这种方式虽好,但是在实际使用中发现了一个限制

​ 传入的命令不能带有引号,否则执行失败。比如:spawn virsh -c 'esx://root@172.16.2.179?no_verify=1' list --all,会报错:no such file or directory。实际工作中免不了要将一些带有特殊字符的参数用引号包起来,这时可以绕一下,将命令写到文件中再执行:

expect执行脚本:pass.sh

shell">#!/bin/expect
set command [lindex $argv 0]
set passwd [lindex $argv 1]
spawn ${command}
expect {
    "*password*" {
        send "${passwd}\r"
        exp_continue
    }
    "*error*" {
        exit 1
    }
    eof {
        exit
    }
}

存储命令的可执行脚本:commond.sh

shell">#!/bin/bash
virsh -c 'esx://root@172.16.2.179?no_verify=1' list --all

然后就可以执行:

shell">./pass.sh ./commond.sh ABCDabcd.1234

此时就达到了自动化输入的目的。

详细的expect使用参考博客:https://www.cnblogs.com/lixigang/articles/4849527.html


http://www.niftyadmin.cn/n/1520620.html

相关文章

python删除字符串中某个字符,用replace()方法来处理

Python replace() 方法把字符串中的 old&#xff08;旧字符串&#xff09; 替换成 new(新字符串)&#xff0c;如果指定第三个参数max&#xff0c;则替换不超过 max 次。 语法 replace()方法语法&#xff1a; str.replace(old, new[, max])参数 old – 将被替换的子字符串。 n…

python判断某个字符串中是否包含某个子字符串,方法:if ’str1‘ in str

使用in方法 实例&#xff1a; str1hello china! if china in str1:print(yes) else:print(no)运行结果&#xff1a; yes参考&#xff1a;链接

leetcode --2.两数相加

给出两个 非空 的链表用来表示两个非负的整数。其中&#xff0c;它们各自的位数是按照 逆序 的方式存储的&#xff0c;并且它们的每个节点只能存储 一位 数字。 如果&#xff0c;我们将这两个数相加起来&#xff0c;则会返回一个新的链表来表示它们的和。 您可以假设除了数字…

Leetcode3.无重复字符的最长子串

给定一个字符串&#xff0c;请你找出其中不含有重复字符的 最长子串 的长度。 示例 1: 输入: "abcabcbb"输出: 3 解释: 因为无重复字符的最长子串是 "abc"&#xff0c;所以其长度为 3。示例 2: 输入: "bbbbb" 输出: 1 解释: 因为无重复字符的最…

Leetcode7.整数翻转

给出一个 32 位的有符号整数&#xff0c;你需要将这个整数中每位上的数字进行反转。 示例 1: 输入: 123 输出: 321示例 2: 输入: -123输出: -321示例 3: 输入: 120 输出: 21注意: 假设我们的环境只能存储得下 32 位的有符号整数&#xff0c;则其数值范围为 [−231, 231 − …

centos7查看yum仓库下所有的rpm包

centos7查看yum仓库下所有的rpm包 # 列出所有仓库中的rpm yum list # 列出某一仓库中的rpm yum repo-pkgs <repo-name> listrepo-pkgs的意思是将yum仓库当作安装包的组&#xff08;Minimal Install、GNOME Desktop等&#xff09;来看待&#xff0c;这样就能后接包或组才…

c++如何输入一个不定长的字符串数组

#include<iostream> #include<vector> #include<string.h> using namespace std;int main(){vector<string> strs;string s;while(cin>>s){strs.push_back(s);}cout<<strs.size();return 0; }每次输入字符串敲一下回车&#xff0c;继续输…