简体   繁体   中英

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.

I know I can file the interface using the commands IP a or ipconfig

    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

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. By this, I presume you mean the interface on which the Web Server is running. Let's assume that this is a standard web server, using the standard ports for the HTTP and HTTPS protocols. So the first thing you need to know is: Is anything listening on those ports on ANY tcp interfaces? For this you need the netstat command:

netstat -na

You can then filter this output looking for specific patterns using sed or grep . 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). It should give you output similar to:

0.0.0.0 443
0.0.0.0 80

For IPv4, 0.0.0.0 means ALL interfaces. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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