AppleScript: how restart automatically the internet connection when it's stuck - macos

When I upload a big amount of files through FTP for some reason my WiFi connection stops working. The connection doesn't show any problem and for solving this it's enough disable and re-enable the wifi. How to restart automatically it using AppleScript in the Script Editor?

My solution's this script that every second checks the connection to google and if there is a timeout close and reopen the en0 connection.
log "Internet checker: let's go"
repeat while true
try
do shell script "nc -w 4 -z 8.8.8.8 53"
# do shell script "nc -w 4 -z apple.com 80"
log "External TCP call test works"
on error
log "Restarting internet..."
do shell script "networksetup -setairportpower Wi-Fi off"
delay 2
do shell script "networksetup -setairportpower Wi-Fi on"
log "Done."
delay 8
end try
delay 2 # wait a moment before the next internet checking
end repeat
Update 24 Aug 022: This should be my 'definitive edition' of the script: privileges are no more requested. It used to be pretty slow to discover the lack of internet connection despite the -w timeout, so I try to ask directly to a "standard de facto" IP (a DNS server).
For more information about nc command you can consult this link: https://www.computerhope.com/unix/nc.htm

Related

Keep ssh tunnel open after running script

I have a device with intermittent connectivity that "calls home" to open a reverse tunnel to allow me to SSH into it. This works very reliably started by systemd and automatically restarted on any exit:
ssh -R 1234:localhost:22 -N tunnel-user#reliable.host
Now however I want to run a script on the reliable-host on connect. This is easy enough with a simple change to the ssh ... cli: swap -N for a script name on the remote reliable-host:
ssh -R 1234:localhost:22 tunnel-user#reliable.host ./on-connect.sh
The problem is that once the script exits, it closes the tunnels if they're not in use.
One workaround I've found is to put a long sleep at the end of my script. This however leaves sleep processes around after the connection drops since sleep doesn't respond to SIGHUP. I could put a shorter sleep in an infinite loop (I think) but that feels hacky.
~/on-connect.sh
#!/bin/bash
# Do stuff...
sleep infinity
How can I get ssh to behave like -N has been used so that it stays connected with no activity but also runs a script on initial connection? Ideally without needing to have a special sleep (or equivalent) in the remote script but, if not possible, proper cleanup on the reliable-host when the connection drops.

tcpprobe does't exist in /proc/net/ when I used SSH

I am new in world of network. I made a simple SDN that contains 3 hosts, one switch and a controller. I would like to monitor the traffic using tcpprobe. I opened a terminal using xterm h1 and ran the shell there. I also made iperf server in h2. But the tcpprobe was not existed in /proc/net/ directory when I use a SSH terminal!
enter image description here
However I installed it on my VM and it is exist in /proc/net/ of my VM.
enter image description here
sudo apt-get install transcode
Here is my shell code:
#!/bin/bash
#used variables
eth=h1-eth0
port_to_probe=5001
#we will probe the iperf port
server_addr=10.0.0.2
#LOAD TCP CONGESTION CONTROL MODULES
modprobe tcp_probe port=$port_to_probe full=1 bufsize=50
for time_test in 10 20 30 60 10 20
do
echo "Traffic transmission time set to " $time_test "s randomly.\n"
#start logging data
sudo cat /proc/net/tcpprobe > tcprobe.dat &
#get the cat process ID to later kill it
pid=$!
#kill the logger
kill $pid
done
Can anybody help me?
The problem was that, each SSH use a port to connect to VM and this cause a change on the address of /proc/net/. To solve this problem it is enough to change the mentioned address to /proc/6337/net/. By reading this address in fact you read the real VM directory. So the final code will change to:
cat /proc/6337/net/tcpprobe

How do I check for internet connection OSX

My iMac wi-fi is a bit unstable. Sometimes it says it's connected and has full signal, but webpages won't load in Safari or Chrome. I have to turn wifi off/on to fix it.
The weird thing is when I ping google.com on Terminal, I have 0% packet loss.
PING www.google.com (68.104.213.123):
56 data bytes 64 bytes from 68.104.213.123: icmp_seq=0 ttl=52 time=21.530 ms
--- www.google.com ping statistics ---
1 packets transmitted, 1 packets received, 0.0% packet loss
round-trip min/avg/max/stddev = 21.530/21.530/21.530/0.000 ms
I made this Apple Script to try to fix this, but it seems like I need another method for checking actual internet connection instead of just pinging. What could I do?
repeat
try
do shell script "ping -o -t 2 www.google.com"
on error
say "Couldn't connect"
do shell script "networksetup -setairportpower en1 off"
do shell script "sleep 5"
do shell script "networksetup -setairportpower en1 on"
end try
delay 60
end repeat
curl www.apple.com will access the internet from terminal
Get inspiration from above question and answer, I changed code as below:
on idle
try
do shell script "curl -m 4 www.google.com"
on error
say "Couldn't connect"
do shell script "networksetup -setairportpower en1 off"
do shell script "sleep 5"
do shell script "networksetup -setairportpower en1 on"
end try
return 60
end idle
Because if you use repeat, you cannot exit program. By using on idle, you can easily exit program at any time. But you MUST save the script as runnable and check the keep it running checkbox when saving.

Detecting the PC is running on UPS Power and shutdown Computer

I'm downloading huge sums of data at night and my PC in running through a UPS. Is there any way I can detect a power failure and command my PC to shut down automatically? Because I work at night, and there's no one to switch off the PC, it would be really helpful if anyone could help. Is it possible?
Thanks.
IMPORTANT: The scripts presented below will cause the system to shutdown whenever the network is down, so use them at your own risk!
A not so elegant way of doing what you want, if you have a network host (e.g. your router) that responds to ICMP echo requests and is not powered by the UPS (or at least the networking equipment is not powered by the UPS), would be to ping that host every few seconds and if it's down then shutdown the PC:
#!/bin/bash
while :
do
ping -c 1 -w 5 192.168.0.1 &> /dev/null
if [ $? -gt 0 ]; then
shutdown -hP now
break
fi
sleep 10s
done
You will have to change 192.168.0.1 to the IP address of the network host you want to ping.
You will also have to make the script executable with chmod +x <script_name> and place a call to it in /etc/rc.local (do not forget to append a & to make it run in the background) which will run the script as root on boot.
For completeness' sake, if the PC was running Windows XP one could use the following batch file:
:loop
ping -n 1 -w 5000 192.168.0.1
if not %ERRORLEVEL% == 0 (
shutdown -s
goto end
)
sleep 10
goto loop
:end
Note that the Windows batch file requires the sleep command which can be installed as part of the Windows Server 2003 Resource Kit Tools package (available as a free download from Microsoft's site)
If it's an APC and it has a data port you can use PowerChute. It's a java-based GUI (which could be a problem if this is your server) that does exactly what you are requesting.

Spawn subshell for SSH and continue with program flow

I'm trying to write a shell script that automates certain startup tasks based on my location (home/campusA/campusB). I go to University and take classes in two different campuses (hence campusA/campusB). My location is determined by which wireless network I'm connected to. For the purposes of this script, we can assume that I will be connected to one of these networks when the script is called and my script knows which one I'm connected to based on a call to iwconfig.
This is what I want it to do:
cat file1 > file2 # always do this, regardless of where I am
if Im at home:
start tweetdeck, thunderbird, skype
else if Im at campusA:
activate the login script # I need to login on a webform before I get internet access.
# I have written a script to automate this.
# Wait for this script to finish before doing anything else
myProg2 & # I want myProg2 running in the background until I shutdown my computer.
else if Im at campusB:
ssh username#domain # this is the problematic line
myProg2 & # I want myProg2 running in the background until I shutdown my computer.
start tweetdeck, thunderbird
close the terminal with the "exit" command
The problem is that campusB's wireless network is behind a firewall, which grants me internet access ONLY after I successfully ssh by username#domain. After a successful ssh, I need to keep the terminal window active in order to hold keep the internet access. If I close the terminal window, I lose internet access (this is bad).
When I try doing just ssh username#domain, the script stops because I don't exit the ssh command. I can't ^C out of it, which means that the rest of the script is never executed. I also have the same problem if I just close the terminal window in an attempt to kill the ssh session.
Some googling brought me to subshell, which I'm either using wrong or can't use to solve my problem. So how should I go about solving this problem? I'd appreciate any help - I've been at this for a while now and am unable to find anything helpful. If it makes a difference, I'd rather not store my ssh password in the script
Further, ampersanding the ssh call (ssh username#domain &) doesn't seem to do any good (can anyone explain why?)
Thank you in advance
EDIT
I must clarify, that the ssh connection has to be active in order for me to have internet access. Thus, when I close the terminal window, I need the ssh connection to still be active.
I had a script that looped on 6 servers, calling via ssh in the background. In 1 part of the script, there was a mis-behaving vendor application; the application didn't 'let go' of the connection properly. (other parts of the script using ssh in background worked fine).
I found that using ssh -t -t cured the problem. Maybe this can help you too.
(a teammate found this on the web, and we had spent so much time, I never went back to read the article that suggested this. The man page on our system gave no hint that such a thing was possible)
Hope this helps.
You may want to try to double background myProg2 to detach it from the tty:
# cf. "Wizard Boot Camp, Part Six: Daemons & Subshells",
# http://www.linux-mag.com/id/5981
(myProg2 &) &
Another option may be to use the daemon tool from the libslack package:
http://ingvar.blog.linpro.no/2009/05/18/todays-sysadmin-tip-using-libslack-daemon-to-daemonize-a-script/
Having a ssh with pseudy tty on background shell
In addition to #shellter's answer, I would like make some precision:
where #shelter said:
The man page on our system gave no hint that such a thing was possible
On my system (Debian 7 GNU/Linux), if I hit:
man -Pcol\ -b ssh| grep -A3 '^ *-t '
I could read:
-t Force pseudo-tty allocation. This can be used to execute arbi‐
trary screen-based programs on a remote machine, which can be
very useful, e.g. when implementing menu services. Multiple -t
options force tty allocation, even if ssh has no local tty.
Yes: Multiple -t options force tty allocation, even if ssh has no local tty.
This mean: If you remotely run a tool that require access to pseudo terminal ( pty like /dev/pts/0), you could run them by using -t switch.
But this would work only if ssh is run from a shell console (aka having his own pty). If you plan to run them is shell session without console, like background scripts, you may use Multiple -t to enforce pseudo tty allocation from ssh.
Multiple ssh shell on one ssh connection
In addition to answers from #tommy and #geekosaur, I would make some precision:
#tommy point to a very intersting feature of ssh. Not sure this have a lot to do with answer, but speaking around long time connection, this feature has to be clearly understood.
Once a connection is established, ssh could (and know how to) use them to drive a lot of thing in this one connection:
-L let you drive remote TCP connections to local machines/network. (full syntax is: -L localip:localport:distip:distport) where localip could be specified to permit other hosts from same local domain to access same tcp bind, and distip could by any host from distant network ( not only localhost ) sample: -L192.168.1.31:8443:google.com:443 permit any host from local domain to reach google through your host: http://192.168.1.31:8443
-R Same remarks in reverse way!
-M Tell ssh to open a local unix socket for bindind next ssh consoles. Simply open two terminal window. First in both window, hit: ssh somewhere than hit netstat -tan | grep :22 or netstat -tan | grep 192.168.1.31:22 (assuming 192.168.1.31 is your onw host's ip)
Than compare close all your ssh session and in first terminal, hit: ssh -M somewhere and in second, simply ssh somewhere. you may see in second terminal:
$ ssh somewhere
+ ssh somewhere
Last login: Mon Feb 3 08:58:01 2014 from elsewhere
If now you hit netstat -tan | grep 192.168.1.31:22 (on any of two oppened ssh session;) you must see that there is only one tcp connection.
This kind of features could be used in combination with -L and maybe some sleep 86399...
To work around a tcp killer router that close every inactive TCP connection from more than 120 seconds, I run:
ssh -M somewhere 'while :;do uptime;sleep 60;done'
This ensure connection stay up even if I dont hit a key for more than two minutes.
Here's a few thoughts that might help.
Sub-shells
Sub-shells fork new processes, but don't return control to the calling shell. If you want to fork a sub-shell to do the work for you, then you'll need to append a & to the line.
(ssh username#domain) &
But this doesn't look like a compelling reason to use a sub-shell. If you had a number commands you wanted to execute in order from each other, yet in parallel from the calling shell, then maybe it would be worth it. For example...
(dothis.sh; thenthis.sh; andthislastthingtoo.sh) &
Forking
I'm not sure why & isn't working for you, but it may be worth looking into nohup as well. This makes the command "immune" to hang up signals.
nohup ssh username#domain (try with and without the & at the end)
Passwords
Not storing passwords in the script is essential for any ssh automation. You can accomplish that using public key cryptography which is an inherent feature of ssh. I wont go into the details here because there are a number of great resources all across the interwebs on setting this up. I strongly suggest investigating this further.
HOWTO: set up ssh keys - Paul Keck, 2001
SSH Keys - archlinux.org
SSH with authentication key instead of password - Debian Administration
Secure Shell - Wikipedia, the free encyclopedia
If you do go this route, I also suggest running ssh in "batch mode" which will disable password querying and will automatically disconnect from the server if it becomes unresponsive after 5 minutes.
ssh -o 'BatchMode=yes' username#domain
Persistence
Then if you want to persist the connection, run some silly loop in bash! :)
ssh -o 'BatchMode=yes' username#domain "while (( 1 == 1 )); do sleep 60; done"
The problem with & is that ssh loses access to its standard input (the terminal), so when it goes to read something to send to the other side it either gets an error and exits, or is killed by the system with SIGTTIN which will implicitly suspend it. The -n and -f options are used to deal with this: -n tells it not to use standard input, -f tells it to set up any necessary tunnels etc., then close the terminal stream.
So the best way to do this is probably to do
ssh -L 9999:localhost:9999 -f host & # for some random unused port
and then manually kill the ssh before logout. Alternately,
ssh -L 9999:localhost:9999 -n host 'while :; do sleep 86400; done' </dev/null &
(The redirection is to make sure the SIGTTIN doesn't happen anyway.)
While you're at it, you may want to save the process ID and shut it down from your .logout/.bash_logout:
ssh -L 9999:localhost:9999 -n host 'while :; do sleep 86400; done' < /dev/null & echo $! >~.ssh_pid; chmod 0600 ~/.ssh_pid
and in .bash_logout:
if test -f ~/.ssh_pid; then
set -- $(sed -n 's/^\([0-9][0-9]*\)$/\1/p' ~/.ssh_pid)
if [ $# = 1 ]; then
kill $1 >/dev/null 2>&1
fi
rm ~/.ssh_pid
fi
The extra code there attempts to avoid someone sabotaging your ~/.ssh_pid, because I'm a professional paranoid.
(Code untested and may have typoes)
It's been a while since I've used ssh, and I can't test it right now, but have you tried the -f switch?
ssh -f username#domain
The man page says it backgrounds ssh. Not sure why & wouldn't work, but I guess it's interpreting it as a command to be run on the remote machine.
Maybe screen + ssh would fit the bill as well?
Something like:
screen -d -m -S sessionName cmd
screen -d -m -S sessionName cmd &
# reconnect with
screen -r sessionName

Resources