Skip to content

Instantly share code, notes, and snippets.

@koonix
Last active July 1, 2021 10:26
Show Gist options
  • Save koonix/2d99aeb418a9231b35e4c438300b8c41 to your computer and use it in GitHub Desktop.
Save koonix/2d99aeb418a9231b35e4c438300b8c41 to your computer and use it in GitHub Desktop.
[Bash Script] Mount FTP servers from a list of servers.
#!/bin/bash
# mount ftp servers from a server list.
# i use it to mount my phone with the
# help of an ftp server android app.
# requires curlftpfs.
# config
hosts=~/.config/mftp/hosts
mntdir=~/Mount/FTP
main ()
{
mkconfig
nocursor
while true; do
fhosts="$(grep -vE '^$|^#' "$hosts")"
clear
echo "choose server"
echo "q: quit"
echo "e: edit server list"
echo "$fhosts" | cut -d, -f1 | nl -w1 -s': '
read -s -n 1 char
case "$char" in
q) exit ;;
e) edit; continue ;;
'') continue ;;
*) [ "$char" -gt 0 ] || continue
esac
mnt="$mntdir/$char"
line="$(echo "$fhosts" | sed "${char}q;d")"
host="$(echo "$line" | cut -d, -f1)"
user="$(echo "$line" | cut -sd, -f2-)"
[ -n "$line" ] || [ -n "$host"] || continue
[ -n "$user" ] && user=",user=$user"
break
done
mnt
! is_mounted && return
while true; do
open
unmnt
! is_mounted && break
done
}
mnt ()
{
mkdir -p "$mnt"
is_mounted && echo already mounted. && return
cleanup
echo "connecting..."
curlftpfs -o utf8"$user" "ftp://$host" "$mnt"
is_mounted && echo mounted. || rmdir "$mnt"
cleanup
}
unmnt ()
{
! is_mounted && echo not mounted. && return 1
fusermount -u "$mnt" && echo unmounted.
rmdir "$mnt"
}
open ()
{
$TERMFILE "$mnt"
}
cleanup ()
{
is_mounted || u >/dev/null 2>&1
}
is_mounted ()
{
[ $(ls -A "$mnt" 2>/dev/null | wc -l) -gt 0 ] && return 0
grep -q "$host" /etc/mtab && return 0
return 1
}
nocursor ()
{
tput civis
trap 'tput cnorm' EXIT
}
edit ()
{
ed="${EDITOR:-$VISUAL}"
[ -z "$ed" ] && ed=xdg-open
$ed "$hosts"
}
mkconfig ()
{
[ -f "$hosts" ] && return 1
mkdir -p "$(dirname "$hosts")"
echo '# list of ftp servers for mftp
# <host:port>[,user:password]
# examples:
ftp.example.com:6969,user:pass
192.168.1.15:2121' > "$hosts"
}
main "$@"
exit
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment