简体   繁体   English

如何将命令 output 复制到 bash 变量中

[英]how to copy command output in to a bash variable

I am making a bash script that needs to know the web interface of the Linux server.我正在制作一个需要知道 Linux 服务器的 web 接口的 bash 脚本。

I know I can file the interface using the commands IP a or ipconfig我知道我可以使用命令IP aipconfig来归档接口

    1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
    inet6 ::1/128 scope host 
       valid_lft forever preferred_lft forever
2: enp0s3: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP group default qlen 1000
    link/ether 08:00:27:3c:20:ec brd ff:ff:ff:ff:ff:ff
    inet 10.0.2.15/24 brd 10.0.2.255 scope global dynamic noprefixroute 
       valid_lft 80057sec preferred_lft 80057sec
    inet6 fe80::7888:1c1e:859a:5c75/64 scope link noprefixroute 
       valid_lft forever preferred_lft forever

in this example, the interface is enp0s3在这个例子中,接口是enp0s3

of course in every server the interface will be different, so what can I do about it?当然,在每台服务器中,界面都会有所不同,那我该怎么办呢?

is there any way that I can copy this data automatically and set it as a variable on the script?有什么方法可以自动复制这些数据并将其设置为脚本上的变量?

thanks!谢谢!

so after a big research, i found a solution所以经过大量研究,我找到了解决方案

I will use this command to copy the interface我将使用此命令复制界面

ip a | grep -o -P '(?<=2: ).*(?=:)'

You want to know the "web interface" of the server.您想知道服务器的“Web 界面”。 By this, I presume you mean the interface on which the Web Server is running.我假设您的意思是Web 服务器正在运行的接口。 Let's assume that this is a standard web server, using the standard ports for the HTTP and HTTPS protocols.假设这是一个标准的 web 服务器,使用 HTTP 和 HTTPS 协议的标准端口。 So the first thing you need to know is: Is anything listening on those ports on ANY tcp interfaces?所以你需要知道的第一件事是:是否有任何东西在任何tcp 接口上的这些端口上监听? For this you need the netstat command:为此,您需要netstat命令:

netstat -na

You can then filter this output looking for specific patterns using sed or grep .然后,您可以使用sedgrep过滤此 output 以查找特定模式。 For example:例如:

netstat -na | sed -ne 's/^tcp[6 ]*[0-9]* *[0-9]* *\([0-9.:]*\):\(\(80\|443\)\) .*LISTEN *$/\1 \2/p'

The sed regular expression looks complex, but it's really not too bad (I can provide an explanation if you wish). sed正则表达式看起来很复杂,但确实还不错(如果您愿意,我可以提供解释)。 It should give you output similar to:它应该给你 output 类似于:

0.0.0.0 443
0.0.0.0 80

For IPv4, 0.0.0.0 means ALL interfaces.对于0.0.0.0表示所有接口。 You then have the IP address(es) of all interfaces that are listening for HTTP or HTTP requests, which you can match to the output of the ip or ifconfig commands. You then have the IP address(es) of all interfaces that are listening for HTTP or HTTP requests, which you can match to the output of the ip or ifconfig commands.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM