determine if connection is wired or wireless? - bash

I have a bash script I made which when run on each of my computers, detects the number of CPU cores, HDDs/partitions, battery present or not, etc, and generate a conkyrc file to display the relevant info for that PC using the style I prefer in my conky. I am having difficulty determining whether the PC is on a wired or wireless internet connection however.
Does anyone know a way to determine the type of connection with a bash script?

Try this:
tail -n+3 /proc/net/wireless | grep -q . && echo "We are wireless"
Details
On a hardwired system, the contents of /proc/net/wireless consist of two header lines:
# cat /proc/net/wireless
Inter-| sta-| Quality | Discarded packets | Missed | WE
face | tus | link level noise | nwid crypt frag retry misc | beacon | 22
On a system with an active wireless interface, there will be a third line displaying data about that interface.
The command above works as follows
The tail -n+3 command is used to remove the header.
The grep -q . command tests for the presence of subsequent lines that are present if a wireless interface is active.
Alternative
iwconfig is a utility that reads information from /proc/net/wireless:
iwconfig 2>&1 | grep -q ESSID && echo "We are wireless"

Related

"WRITE" command works manually but not via script

My Co-Workers and I use the screen program on our Linux JUMP server to utilize as much screen space as possible. With that, we have multiple screens setup so that messages can go to one while we do work in another.
With that, i have a script that is used to verify network device connectivity which will send messages to my co-workers regardless if there is anything down or not.
The script initially references a file with their usernames in it and then grabs the highest PTS number which denotes the last screen session they activated and then puts it into the proper format in an external file like such:
cat ./netops_techs | while read -r line; do
temp=$(echo $line)
temp2=$(who | grep $temp | sed 's/[^0-9]*//g' | sort -n -r | head -n1)
if who | grep $temp; then
echo "$temp pts/$temp2" >> ./tech_send
fi
done
Once it is done, it will then scan our network every 5 minutes and send updates to the folks in the file "./tech_send" like such:
Techs=$(cat ./tech_send)
if [ ! -f ./Failed.log ]; then
echo -e "\nNo network devices down at this time."
for d in $Techs
do
cat ./no-down | write $d
done
else
# Writes downed buildings localy to my terminal
echo -e "\nThe following devices are currently down:"
echo ""
echo "IP Hostname Model Building Room Rack Users Affected" > temp_down.log
grep -f <(sed 's/.*/\^&\\>/' Failed.log) Asset-Location >> temp_down.log
cat temp_down.log | column -t > Down.log
cat Down.log
# This will send the downed buildings to the rest of NetOps
for d in $Techs
do
cat Down.log | write $d
done
fi
The issue stems from, when they are working in their main sectioned screen, the messages will pop up in that active screen instead of the inactive screen. If I send them a message manually such as:
write jsmith pts/25
Test Test
and then CTRL+D, it works fine even if they are in a different session. Via script though, it gives an error stating that:
write: jsmith is logged in more than once; writing to pts/23
write: jsmith/pts/25 is not logged in
I have verified the "tech_send" file and it has the correct format for them:
jsmith pts/25
Would appreciate any insight on why this is happening.

How to delete a connection by type with nmcli?

I want to have a bash script that can delete all my network manager connections of type gsm with nmcli.
What is the best approach for this?
This is actually a trickier question than it seems on the surface, because NetworkManager allows for connection names with spaces in them. This makes programmatic parsing of the output of nmcli connection show for connection names a bit awkward. I think the best option for scripting would be to rely on the UUID, since it seems to consistently be a 36 character group of hexidecimal characters and dashes. This means we can pull it consistently with a regular expression. So for example you could get a list of the UUIDs for gsm connections with the following:
$ nmcli connection show | grep gsm | grep -E -o '[0-9a-f\-]{36}'
cc823da6-d4e1-4757-a37a-aaaaaaaaa
etc
So you could grab the UUIDs and then delete based on the UUID:
GSM_UUIDS=$(nmcli connection show | grep gsm | grep -E -o '[0-9a-f\-]{36}')
while IFS= read -r UUID; do echo nmcli connection delete $UUID; done <<< "$GSM_UUIDS"
Run with the echo to make sure you're getting the result you expect, then you can remove it and you should be in business. I ran locally with some dummy GSM connections and it seemed to work they way you would want it to:
GSM_UUIDS=$(nmcli connection show | grep gsm | grep -E -o '[0-9a-f\-]{36}')
while IFS= read -r UUID; do nmcli connection delete $UUID; done <<< "$GSM_UUIDS"
Connection 'gsm' (cd311376-d7ab-4891-ba73-e4e8a3fc6614) successfully deleted.
Connection 'gsm-1' (54171181-5c37-4224-baf5-9eb36458f773) successfully deleted.
nmcli con del $(nmcli -t -f UUID,TYPE con | awk -F":" '{if ($2 == "gsm") print $1}')

I want to retrieve battery related information(Model information,health information,charge information) through terminal in mac os

I have tried the following command in macOS to get all the battery information:
pmset -g batt
The above command is displaying only one information(i.e 35% discharging).
system_profiler SPPowerDataType | grep "Device Name" | awk '{print $3}'
The above command is displaying device name.
Is there any command by using which together all battery information(Serial Number, Manufacturer, device name, cycle count, charging, etc.),we can fetch. Please help me in finding this. Thanks for your help in advance.
The best command that I could think of is
ioreg -w0 -1 | grep Capacity
For me this returns something like this:
| | "AppleRawCurrentCapacity" = 6417
| | "AppleRawMaxCapacity" = 6834
| | "MaxCapacity" = 6834
| | "CurrentCapacity" = 6417
| | "LegacyBatteryInfo" = {"Amperage"=18446744073709550119,"Flags"=4,"Capacity"=6834,"Current"=6417,"Voltage"=8204,"Cycle Count"=198}
| | "DesignCapacity" = 7150
| | "BatteryData" = {"StateOfCharge"=24064,"Voltage"=8204,"QmaxCell1"=46108,"ResScale"=0,"QmaxCell2"=0,"QmaxCell0"=54044,"CycleCount"=198,"DesignCapacity"=7150}
Don't forget that you can combine multiple commands into one to run after the other has completed with && eg:
system_profiler SPPowerDataType | grep "Device Name" | awk '{print $3}' && ioreg -w0 -1 | grep Capacity
You can also replace the word Capacity with things like board-id
If you want to process all this data I would create a bash script to do it for you,
Because you can cut up the lines to display the info that you want like:
ioreg -l | grep board-id | cut -d \" -f 4
Obviously you can just type this into the terminal but doing this for every command gets a bit tyresome!
Combine many of these commands to make a script (or even in python!) that would process all the data and return it in anyway you would like, if that is possible for what you want to use that data for!
I should think that all the possible accessible battery information is found in system information > power:
Battery Information:
Model Information:
Manufacturer: DP
Device Name: bq20z451
Pack Lot Code: 0
PCB Lot Code: 0
Firmware Version: 511
Hardware Revision: 000a
Cell Revision: 1210
ETC.....
EDIT:
Istats is a free CLI which allows you to view a lot of info but is obviously not native see https://robservatory.com/see-sensor-stats-in-terminal/
To find the battery temp with a single native command! :
bc <<< "scale=3; `ioreg -r -n AppleSmartBattery | grep Temperature | cut -c23-`/100"
Hope this helps

Get Macbook screen size from terminal/bash

Does anyone know of any possible way to determine or glean this information from the terminal (in order to use in a bash shell script)?
On my Macbook Air, via the GUI I can go to "About this mac" > "Displays" and it tells me:
Built-in Display, 13-inch (1440 x 900)
I can get the screen resolution from the system_profiler command, but not the "13-inch" bit.
I've also tried with ioreg without success. Calculating the screen size from the resolution is not accurate, as this can be changed by the user.
Has anyone managed to achieve this?
I think you could only get the display model-name which holds a reference to the size:
ioreg -lw0 | grep "IODisplayEDID" | sed "/[^<]*</s///" | xxd -p -r | strings -6 | grep '^LSN\|^LP'
will output something like:
LP154WT1-SJE1
which depends on the display manufacturer. But as you can see the first three numbers in this model name string imply the display-size: 154 == 15.4''
EDIT
Found a neat solution but it requires an internet connection:
curl -s http://support-sp.apple.com/sp/product?cc=`system_profiler SPHardwareDataType | awk '/Serial/ {print $4}' | cut -c 9-` |
sed 's|.*<configCode>\(.*\)</configCode>.*|\1|'
hope that helps
The next script:
model=$(system_profiler SPHardwareDataType | \
/usr/bin/perl -MLWP::Simple -MXML::Simple -lane '$c=substr($F[3],8)if/Serial/}{
print XMLin(get(q{http://support-sp.apple.com/sp/product?cc=}.$c))->{configCode}')
echo "$model"
will print for example:
MacBook Pro (13-inch, Mid 2010)
Or the same without perl but more command forking:
model=$(curl -s http://support-sp.apple.com/sp/product?cc=$(system_profiler SPHardwareDataType | sed -n '/Serial/s/.*: \(........\)\(.*\)$/\2/p')|sed 's:.*<configCode>\(.*\)</configCode>.*:\1:')
echo "$model"
It is fetched online from apple site by serial number, so you need internet connection.
I've found that there seem to be several different Apple URLs for checking this info. Some of them seem to work for some serial numbers, and others for other machines.
e.g:
https://selfsolve.apple.com/wcResults.do?sn=$Serial&Continue=Continue&num=0
https://selfsolve.apple.com/RegisterProduct.do?productRegister=Y&country=USA&id=$Serial
http://support-sp.apple.com/sp/product?cc=$serial (last 4 digits)
https://selfsolve.apple.com/agreementWarrantyDynamic.do
However, the first two URLs are the ones that seem to work for me. Maybe it's because the machines I'm looking up are in the UK and not the US, or maybe it's due to their age?
Anyway, due to not having much luck with curl on the command line (The Apple sites redirect, sometimes several times to alternative URLs, and the -L option doesn't seem to help), my solution was to bosh together a (rather messy) PHP script that uses PHP cURL to check the serials against both URLs, and then does some regex trickery to report the info I need.
Once on my web server, I can now curl it from the terminal command line and it's bringing back decent results 100% of the time.
I'm a PHP novice so I won't embarrass myself by posting the script up in it's current state, but if anyone's interested I'd be happy to tidy it up and share it on here (though admittedly it's a rather long winded solution to what should be a very simple query).
This info really should be simply made available in system_profiler. As it's available through System Information.app, I can't see a reason why not.
Hi there for my bash script , under GNU/Linux : I make the follow to save
# Resolution Fix
echo `xrandr --current | grep current | awk '{print $8}'` >> /tmp/width
echo `xrandr --current | grep current | awk '{print $10}'` >> /tmp/height
cat /tmp/height | sed -i 's/,//g' /tmp/height
WIDTH=$(cat /tmp/width)
HEIGHT=$(cat /tmp/height)
rm /tmp/width /tmp/height
echo "$WIDTH"'x'"$HEIGHT" >> /tmp/Resolution
Resolution=$(cat /tmp/Resolution)
rm /tmp/Resolution
# Resolution Fix
and the follow in the same script for restore after exit from some app / game
in some S.O
This its execute command directly
ResolutionRestore=$(xrandr -s $Resolution)
But if dont execute call the variable with this to execute the varible content
$($ResolutionRestore)
And the another way you can try its with the follow for example
RESOLUTION=$(xdpyinfo | grep -i dimensions: | sed 's/[^0-9]*pixels.*(.*).*//' | sed 's/[^0-9x]*//')
VRES=$(echo $RESOLUTION | sed 's/.*x//')
HRES=$(echo $RESOLUTION | sed 's/x.*//')

Counting context switches per thread

Is there a way to see how many context switches each thread generates? (both in and out if possible) Either in X/s, or to let it run and give aggregated data after some time.
(either on linux or on windows)
I have found only tools that give aggregated context-switching number for whole os or per process.
My program makes many context switches (50k/s), probably a lot not necessary, but I am not sure where to start optimizing, where do most of those happen.
On recent GNU/Linux systems you can use SystemTap to collect the data you want on every call to sched_switch(). The schedtimes.stp example is probably a good start: http://sourceware.org/systemtap/examples/keyword-index.html#SCHEDULER
Linux
I wrote a small script to see the details of a specific thread of the process. By executing this script you can see context switch as well.
if [ "$#" -ne 2 ]; then
echo "INVALID ARGUMENT ERROR: Please use ./see_thread.sh processName threadNumber"
exit
fi
ls /proc/`pgrep $1`/task | head -n$2 | tail -n+$2>temp
cat /proc/`pgrep $1`/task/`cat temp`/sched
Hope this will help.
I've a bash script that calculates voluntary and non-voluntary context switches made by a thread during a specific time frame. I'm not sure whether this will serve your purpose but I'll post it anyway.
This script is looping over all threads of a process and recording "voluntary_ctxt_switches" & "nonvoluntary_ctxt_switches" from /proc/< process-id>/task/< thread-id>/status. What I do generally is record these counters at the start of a performance run and record again at the end of the run and then calculate difference as total vol & non-vol ctx switches during the performance run.
pid=`ps -ef | grep <process name> | grep $USER | grep -v grep | awk '{print $2}'`
echo "ThreadId;Vol_Ctx_Switch;Invol_Ctx_Switch"
for tid in `ps -L --pid ${pid} | awk '{print $2}'`
do
if [ -f /proc/$pid/task/$tid/status ]
then
vol=`cat /proc/$pid/task/$tid/status | grep voluntary_ctxt_switches | grep -v nonvoluntary_ctxt_switches | awk '{print $NF}'`
non_vol=`cat /proc/$pid/task/$tid/status | grep nonvoluntary_ctxt_switches | awk '{print $NF}'`
fi
echo "$tid;$vol;$non_vol"
done
Script is bit heavy, in my case process has around 2500 threads. Total time to collect ctx switches is around 10 seconds.

Resources