How to run Multiple Terminal Sessions on Linux VPS Server

maxresdefault

In this article, I will introduce you with one of the handy tool for your vps servers. It is an extremely useful app for maintaining multiple terminal sessions through just one window! This Command Line Utility is called Screen.

You may think of it as a Manager who manages different terminal sessions for you using shell. You don’t even need a X Server to run it!

How to Install Screen?

You can install it by typing the following commands:

sudo apt update 
sudo apt install screen

The above command should work on distros like Ubuntu 16.04 LTS, Xubuntu or, debian etc. If you have a different distro find appropriate installation information for it.

Common Commands of Screen

Try running the following command after successful installation:

screen

The output of the above command will be oddly surprising! You will see some texts about screen and you will be in terminal again!

Actually, the screen is running now! you can verify it by pressing `​ctrl+a ?` the output will be:

                       Screen key bindings, page 1 of 2.

                       Command key:  ^A   Literal ^A:  a

  break       ^B b         license     ,            removebuf   =         
  clear       C            lockscreen  ^X x         reset       Z         
  colon       :            log         H            screen      ^C c      
  copy        ^[ [         login       L            select      '         
  detach      ^D d         meta        a            silence     _         
  digraph     ^V           monitor     M            split       S         
  displays    *            next        ^@ ^N sp n   suspend     ^Z z      
  dumptermcap .            number      N            time        ^T t      
  fit         F            only        Q            title       A         
  flow        ^F f         other       ^A           vbell       ^G        
  focus       ^I           pow_break   B            version     v         
  hardcopy    h            pow_detach  D            width       W         
  help        ?            prev        ^H ^P p ^?   windows     ^W w      
  history     { }          quit        \            wrap        ^R r      
  info        i            readbuf     <            writebuf    >         
  kill        K k          redisplay   ^L l         xoff        ^S s      
  lastmsg     ^M m         remove      X            xon         ^Q q      

                  [Press Space for next page; Return to end.]

 

well, ctrl+a is a shortcut for different screen commands and the above output lists all of them! Feel free to explore all of them, as they will be quite handy!

I really liked this digital ocean’s tutorial of Screen commands. Read it if you want to learn the basics of screen

Helpful Resources:

How to create a .torrent file to share files or directories with a self hosted Private Tracker in Linux

What is Torrent File?

Torrent File contains metadata of file system and directories that you want to distribute using the BitTorrent File Distribution System. Along with the meta data it also contains list of trackers. The Network location of trackers are noted in the tracker list.

According to wikipedia:

BitTorrent tracker is a special type of server, one that assists in the communication between peers using the BitTorrent protocol. In peer-to-peer file sharing, a software client on an end-user PC requests a file, and portions of the requested file residing on peer machines are sent to the client, and then reassembled into a full copy of the requested file. The “tracker” server keeps track of where file copies reside on peer machines, which ones are available at time of the client request, and helps coordinate efficient transmission and reassembly of the copied file. Clients that have already begun downloading a file communicate with the tracker periodically to negotiate faster file transfer with new peers, and provide network performance statistics; however, after the initial peer-to-peer file download is started, peer-to-peer communication can continue without the connection to a tracker.

Alright, now that we know about torrent file and trackers lets just jump right into it 🙂

You will need:

  • A Computer to use it as a server. A LINUX based VPS Server is recommended though.  You can get one from Linode. It is quite cheap and very stable (around 5$ per month)
    Use my referral to get free credits:
    https://www.linode.com/?r=00453cca3ebd20582030ca874fbdd626a88b66cd
  • For this tutorial I’m gonna use Ubuntu 16.04 LTS, but you can choose any debian based distro and it should work.
  • Idea of Basic Linux commands & file structure

Setting up a VPS on Linode

You can use the Linode Promo code: DOCS10 to get 10$ credit on a new account! Linode’s documentation is great! It will get you started in minutes. Once you complete this return to this article.
Note: It is always a good idea to secure your vps server as much as possible. So, use a strong password for the root user and, optionally you can install packages like fail2ban, ufw etc.  You can also follow this instructions if you like.

Install Dependencies

Once, you are done with initial vps setup. Follow the following instructions to install the necessary packages for creating our own torrent tracker. Here we will be using bittornado & ctorrent for creating tracker and torrent file respectively. We will also use screen command to run multiple terminal sessions. To install all of them you can run the following command:

apt install bittornado ctorrent screen

Start the tracker

Now that, we have screen installed, we can create a new screen terminal session by running the command:

screen

You will be redirected to a new terminal prompt. You can check out the various screen commands by pressing ctrl+A ? (press ‘enter’ or, hit ‘return’ to exit the help menu)

In the new screen session, you can start your tracker by running the following commands:

mkdir ~/.bttrack
bttrack --port 6969 --dfile ~/.bttrack/dstate --logfile ~/.bttrack/tracker.log --nat_check 0 --scrape_allowed full

The first command will create a new hidden directory in your home folder called ​bttrack and the second command will start your own private torrent tracker!

Detach the screen session by pressing ctrl+A d

It will switch you back to the terminal and keep the tracker running in background screen terminal session which you can resume later if you wish.

Upload your File/Directory to VPS

You will have to upload the file/directory that you wish to share using .torrent file on your vps, In order to seed it from your vps using your private tracker. There are numerous ways to upload files on vps, I prefer ssh though.

If you have enabled ssh login to your server from your local computer. You can share your file with a single scp command from your local computer:

scp -r <source_file_path_of_your_local_directory>  <user>@<ip_address>:<destination_file_path>

example from my local computer I typed:

scp -r  ~/Desktop/MyFile/torrent_this.mp4 root@127.000.000.001:/MyFile/torrent_this.mp4

Here I’m uploading my ​ torrent_this.mp4 file to my vps using ssh. Note that, my username is root and ip address is 127.000.00.001 you will have to put your  username & ip address instead of those.

Creating .torrent file using ctorrent

So far, we have enabled our tracker and uploaded the file we wished to share using torrent. Now, lets make the .torrent file using ctorrent, the command is quite simple!

ctorrent -t -u "http://YOUR_SERVER_IP:6969/announce" -s torrent_file_name.torrent file_or_folder_for_torrent

It will create a .torrent file in the current directory! Voila!

Seed your .torrent file

to seed your .torrent file. Just run the command screen from the torrent file/directory location and run the command:

screen ctorrent torrent_file_name.torrent

It will start to seed your torrent file.  Press ctrl+A d to detach the screen session and keep seeding in background. Now you can distribute your .torrent file.

People will be able to download it and seed it using any torrent client!

 

How to take Password input in Python

Did you know? There is a python module in Python Standard Library called getpass. The purpose of this library is to securely take input from user!

The module is very handy for sensitive inputs such as passwords / keys or any kind of credentials.

Simplest example of getpass could be this:

import getpass
password = getpass.getpass("enter password:")

The code is pretty straight forward! This password prompt will act similarly to unix password prompt, and it won’t echo user inputs (i.e. the key presses) hence, the password you type won’t be visible to end users. The best thing about this module is it is cross platform. So, you can use it on Windows, Linux or Mac.

There are only two functions listed in  The official documentation.
These are:

  •  getpass() – password prompt
  • getuser() – collects username from different environment variables

But, there are more than that, let me show you 😉

>>> import getpass
>>> dir(getpass)
['GetPassWarning', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_raw_input', 'contextlib', 'fallback_getpass', 'getpass', 'getuser', 'io', 'os', 'sys', 'termios', 'unix_getpass', 'warnings', 'win_getpass']

If you inspect carefully you will notice there are two more functions listed in the __dir__

  • unix_getpass( )
    unix_getpass(prompt='Password: ', stream=None)
     Prompt for a password, with echo turned off.
     
     Args:
     prompt: Written on stream to ask for the input. Default: 'Password: '
     stream: A writable file object to display the prompt. Defaults to
     the tty. If no tty is available defaults to sys.stderr.
     Returns:
     The seKr3t input.
     Raises:
     EOFError: If our input tty or stdin was closed.
     GetPassWarning: When we were unable to turn echo off on the input.
     
     Always restores terminal settings before returning.
  • win_getpass( )
    Help on function win_getpass in module getpass:
    
    win_getpass(prompt='Password: ', stream=None)
     Prompt for password with echo off, using Windows getch().

The docstring of these functions tells it all doesn’t it? 🙂

Note that, the win_getpass function uses the Windows getch() so, it requires the msvcrt module.