【shell】实现交互

您所在的位置:网站首页 linux与shell 【shell】实现交互

【shell】实现交互

#【shell】实现交互| 来源: 网络整理| 查看: 265

目录

一、SHELL

1.1 输入单个指令

1.2 输入多行指令

限制输入内容的个数

控制输入内容的可见性

 二、Expect (自动输入yes/no、密码等)

简介

for 中嵌套 expect

在expect中使用shell的环境变量

实例

SSH登录

 FTP文件同步

如何自动输入密码

自动交互方法一:利用命令的自带参数,将标准输入作为手动输入的内容

自动交互方法2:利用expect脚本自动登陆

给用户SDS_Admin做免密登录

Shell脚本read读取从键盘输入

一、SHELL

1.1 输入单个指令

自动输入yes

echo "y" | yum install wget ,等同于yum -y  install wget

自动输入回车

echo -e "\n" | yum remove wget

**`echo -e` 的小知识**

若字符串中出现以下字符,则特别加以处理,而不会将它当成一般文字输出:\a 发出警告声;\b 删除前一个字符;\c 最后不加上换行符号;\f 换行但光标仍旧停留在原来的位置;\v 与\f 相同;\n 换行且光标移至行首;\r 光标移至行首,但不换行;\t 插入 tab 符号;\\ 插入 ‘' 字符;\nnn 插入 nnn(八进制)所代表的 ASCII 字符;

1.2 输入多行指令

输入多行指令我们需要借助输入重定向操作符  There are two approaches: > 1.) per environment: > hostname=10.0.0.1; export hostname > expect -c ' > set timeout 15 > spawn telnet $env(hostname) > ... > '

除非执行完expect后主动 unset hostname,否则其他程序也会读到这个变量,对于公共变量来说,你的修改会影响其他程序。

Unless you explicitly unset hostname after the call to expect, you might pass the hostname also to other utilities called from your script later. This is probably no problem for the hostname, but could be for the password.

> hostname=10.0.0.1 expect -c ' > ... ditto with $env(hostname) > '

这个例子中hostname只是当做环境变量传给expect,然后遗忘,如果你在后续sh脚本中还要用这个变量则不要用这个方法。

In this case, hostname is only passed to expect as an environment variable, and forgotten afterwards, so if you still need the hostname afterwards in the sh-script, don't use it this way.

hostname=10.0.0.1 hostname=$hostname expect -c ' ... ' may appear moronic, but isn't at all. It leaves hostname as a non-exported variable, while still sending it to expect.

> 2.) by concatenating differently quoted strings in sh: > hostname=10.0.0.1 > expect -c ' > set timeout 15 > spawn telnet '"$hostname"' > ... > '

这个方法是不安全的:

Actually, I'm sorry for having posted it at all, because it is maximally unsafe. Any magic characters in the value of hostname could create havoc inside expect, as expect sees its value as unquoted(!) part of the script rather than as the contents of some variable or array.

For hostnames set explicitly in the shell-script this is a non-issue, but I don't know, if this wasn't just a simplification of your problem for posting.

方法一实例:

how to use shell variable in expect session?--https://stackoverflow.com/questions/40376587/how-to-use-shell-variable-in-expect-session

#!/bin/sh IP_LIST=('127.0.0.x' '127.0.0.y' '127.0.0.z') for ip_addr in "${IP_LIST[@]}" do echo "$ip_addr" ip_addr=$ip_addr expect


【本文地址】


今日新闻


推荐新闻


    CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3