I am writing a script that stores client connection data such as session ID, server, and port in an associative array. I need to ssh onto these hosts, and run an lsof command to find what process is using this port.
declare -A HOSTMAP
HOSTMAP[session]=$session_ids
HOSTMAP[cname]=$cnames
HOSTMAP[port]=$ports
When printed, data in the array is displayed as so (host names and ports have been changed to protect the innocent)
for g in "${!HOSTMAP[@]}"
do
printf "[%s]=%s\n" "$g" "${HOSTMAP[$g]}"
done
[cname]=hostname1
hostname2
hostname3
hostname4
hostname5
hostname6
hostname7
hostname8
[session]=44
5
3
9
14
71
65
47
[port]=11111
22222
33333
44444
55555
66666
77777
88888
I would like to do an operation akin to the following:
for session in $session_id
do
echo "Discovering application mapped to session ${session} on ${cname}:${port}"
ssh -tq ${cname} "lsof -Tcp | grep ${port}"
done
Many thanks in advance for advising on an elegant solution
bash
doesn't allow nesting of arrays. Here, I would just use separate indexed arrays. However, since your session appears to be an integers, and indexed arrays are sparse, you can use the session id as the index for the cnames and the ports.
cnames=([44]=hostname1 [5]=hostname2 [3]=hostname3)
ports=([44]=1111 [5]=2222 [3]=3333)
for session in "${!cnames[@]}"; do
cname=${cnames[$session]}
port=${ports[$session]}
echo "Discovering application mapped to session ${session} on ${cname}:${port}"
ssh -tq ${cname} "lsof -Tcp | grep ${port}"
done
You can assign the output of ssh
to a variable
result=$(ssh -tq ${cname} "lsof -Tcp | grep ${port}")
Then you can extract the data you want from $result
.
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.