208 Notes
+ Mount FreeBSD Partition (Jan. 31, 2023, 10:59 a.m.)

mount -t ufs -o ufstype=ufs2 /dev/vdb1 /mnt/

+ Set bash as default shell (Jan. 27, 2023, 5:13 p.m.)

# chsh -s /usr/local/bin/bash {username} # chsh -s bash # bash

+ D-Bus (Desktop Bus) (Jan. 18, 2023, 1:34 p.m.) --------------------------------------------------------------------------------------- D-Bus is a mechanism for interprocess communication under Linux and other Unix-like systems which provides a mechanism for applications to talk to each other. Every modern Linux desktop environment uses D-Bus, a system for allowing software applications to communicate with each other. Thanks to D-Bus, you can make your desktop work the way you want. With D-Bus, every program that offers services to other programs registers itself. Other programs then can look up which services are available. A program also is able to register itself for events, which some system services do, for example, to detect hot-swapping hardware. --------------------------------------------------------------------------------------- Message: A message is the unit of data transfer between processes. A message has a header, which identifies its sender, receiver, method (signal) name, and message body that contains a data payload. --------------------------------------------------------------------------------------- Message Types: There are four types of messages, SIGNAL, METHOD_CALL, METHOD_RETURN, and ERROR. A SIGNAL is a message that is broadcast by a process and can be received by other interested processes. A METHOD_CALL message is a request by the sender for a particular operation on an object of the receiver. For example, the receiver may be a service with a singleton object. The sender could be a client, requesting the execution of a "method" by the server. The method call message has the name of the method to be executed and also the arguments required for execution. The receiver is required to execute the method and respond back to the sender with a METHOD_RETURN message containing the result(s) of the operation. Or, if there was an error, the receiver can respond with an ERROR message. --------------------------------------------------------------------------------------- Message bus A message bus is a daemon process that routes messages between other processes. --------------------------------------------------------------------------------------- Service A service is a daemon process that provides some utility in the system. A service is a server process that does work for the clients. A service has a singleton object. --------------------------------------------------------------------------------------- Object An object is an entity in a process, which does some work. An object is identified by a path name. A path is like a complete file name in the system. So, an object might have a path name like, /com/example/some server. An object has members, which means methods and signals. --------------------------------------------------------------------------------------- Interfaces An interface is a group of functions. An object supports one or more interfaces. The interfaces supported by an object specify the members of that object. --------------------------------------------------------------------------------------- Connection names When an application connects with the D-Bus daemon, it is assigned a unique connection name. A unique connection name starts with the colon character ":". An application may also ask for a well-known name to be assigned to a connection. This is in the form of a reverse domain name like com.example.some_name. --------------------------------------------------------------------------------------- D-Bus Configuration The D-Bus daemon configuration files are located in the /usr/share/dbus-1 directory. ---------------------------------------------------------------------------------------

+ Gnome - Disable Dock Hotkeys (Jan. 12, 2023, 3:06 p.m.)

gsettings set hot-keys false

+ 2> (Dec. 6, 2022, 4:17 p.m.)

File descriptor 2 represents standard error. Other special file descriptors include 0 for standard input and 1 for standard output. 2> /dev/null means to redirect standard error to /dev/null. /dev/null is a special device that discards everything that is written to it.

+ Remmina (Nov. 15, 2022, 10:25 p.m.)

apt install -t stretch-backports remmina remmina-plugin-rdp remmina-plugin-secret remmina-plugin-spice remmina-plugin-vnc apt search remmina plugin

+ Transmission (Nov. 12, 2022, 12:18 p.m.)

Torrent location: ~/.config/transmission/torrents

+ Control SSH Login by Time (Oct. 20, 2022, 2:09 a.m.)

1- Open the following file: vim /etc/pam.d/sshd 2- Add the following line to the file: account required 3- Edit the file "time.conf" to configure when the specific times the users can log in: vim /etc/security/time.conf sshd;*;mohsen;Al0800-2000 User "mohsen" can log into the system using SSH from 8:00 am to 8:00 pm. ------------------------------------------------------------------ The available day options: Mo: Monday Tu: Tuesday We: Wednesday Th: Thursday Fr: Friday Sa: Saturday Su: Sunday Wk: Week days Wd: Week-end Days Al: All 7 Days of the Week ------------------------------------------------------------------ Except: use the exclamation point “!” to say “not”. sshd;*;mohsen;!Wk0800-1700 Now, the "mohsen" user can log in at any time except for week-days between 8:00 am and 5:00 pm. ------------------------------------------------------------------ Specifying Multiple Days: sshd;*;mohsen;MoWeFr1000-1400 ------------------------------------------------------------------ Multiple Users: sshd;*;mohsen|hadi;SaSu0800-2200 ------------------------------------------------------------------ Logs for users' authentications: tail -f /var/log/auth.log ------------------------------------------------------------------ Forcing Logout of Users: sudo crontab -e 0 17 * * 1-5 /usr/bin/pkill -KILL -u mohsen ------------------------------------------------------------------

+ Disk usage for hidden directorie (Oct. 10, 2022, 11:21 a.m.)

du -sh .[^.]*

+ Add GPG public key (PUBKEY) to the apt key manager (Oct. 1, 2022, 1:17 a.m.)

sudo apt-key adv --keyserver --recv-keys 68980A0EA10B4DE8

+ List keys added to ssh-agent (Aug. 26, 2022, 10:56 a.m.)

ssh-add -l Get the full key in OpenSSH format ssh-add -l

+ Install OpenSSL 3 (Aug. 20, 2022, 10:47 p.m.)

Installing this OpenSSL will not solve the problem of the Python compilation requirement for the _ssl module. You need to go to Python Installation in my notes and see how to provide the path of this extracted OpenSSL file. But if you need to install OpenSSL for other purposes, follow these steps. ------------------------------------------------------------- 1- Download OpenSSL 3.0, extract and CD to it: 2- Compile, make, and install OpenSSL: cd /usr/src/openssl-3.0.0 ./config make make install 3- Create symlinks to libssl and libcrypto: ln -s /usr/local/lib64/ /usr/lib64/ ln -s /usr/local/lib64/ /usr/lib64/ 4- Test the installed version with: openssl version

+ Error - Failed to mount (July 30, 2022, 6:21 p.m.)

Failed to mount '/dev/sdb1': Input/output error NTFS is either inconsistent, or there is a hardware fault, or it's a SoftRAID/FakeRAID hardware To fix this error: sudo ntfsfix /dev/sdb1

+ zgrep (June 3, 2022, 10:43 a.m.)

Syntax: zgrep -c "exception" logs.txt.gz zgrep ismail auth.log.2.gz auth.log.3.gz auth.log.4.gz zgrep ismail auth.log.*.gz zgrep -e "ismail" -e "ahmet" auth.log.2.gz zgrep -i 'stop|shutdown' ----------------------------------------------------------------------------- -c : This option is used to display the number of matching lines for each file. -i : This option is used to ignore case sensitivity. -n : This option is used to display the line number of files if the given expression is present in the line. -v : This option is used to display the lines which don’t have the expression present in them. Basically, invert the search function. -e : This option is used to specify the expression but can be used multiple times. -o : This option is used to display only the matched section of the line from the given expression. -l : This option is used to display the names of the files with the expression present in them. -w : By default, zgrep command displays lines even if the expression is found as a sub-string. This option only displays lines only if the whole expression is found. -h : This option is used to display the matched lines but doesn’t display the file names. -s supresses errors about unreadable files that may clutter the output -----------------------------------------------------------------------------

+ Reset xfce panels (May 31, 2022, 9:43 a.m.)

xfce4-panel --quit pkill xfconfd rm -rf ~/.config/xfce4/panel rm -rf ~/.config/xfce4/xfconf/xfce-perchannel-xml/xfce4-panel.xml xfce4-panel

+ Screen (Jan. 19, 2022, 1:06 p.m.)

screen -ls --------------------------------------------------------------------------- Restore the screen: screen -r screen -r 7849 ---------------------------------------------------------------------------

+ Compare Two Directories (Dec. 28, 2021, 1:38 a.m.)

diff --brief --recursive Dir1 Dir2

+ Set volume from terminal (Nov. 20, 2021, 1:11 p.m.)

Increase volume: amixer -q -D pulse sset Master 10%+ Decrease volume: amixer -q -D pulse sset Master 10%- Toggle mute: amixer -q -D pulse sset Master toggle

+ Free up root partition (Nov. 17, 2021, 1:17 p.m.)

- Journal logs ( logs) - Delete old kernels ( old kernels) - du -sh /var/cache/apt apt clean

+ Bash shortcuts (Nov. 10, 2021, 10:24 p.m.)

Command Editing Shortcuts: Ctrl + a – go to the start of the command line Ctrl + e – go to the end of the command line Ctrl + k – delete from cursor to the end of the command line Ctrl + u – delete from cursor to the start of the command line Ctrl + w – delete from cursor to start of word (i.e. delete backwards one word) Ctrl + y – paste word or text that was cut using one of the deletion shortcuts (such as the one above) after the cursor Alt + t – swap current word with previous ---------------------------------------------------------------------------------------------- Command Recall Shortcuts: Ctrl + r – search the history backwards Ctrl + g – escape from history searching mode Ctrl + p – previous command in history (i.e. walk back through the command history) Ctrl + n – next command in history (i.e. walk forward through the command history) ---------------------------------------------------------------------------------------------- Command Control Shortcuts: Ctrl + l – clear the screen Ctrl + s – stops the output to the screen (for long-running verbose commands) Ctrl + q – allow output to the screen (if previously stopped using the command above) Ctrl + c – terminate the command Ctrl + z – suspend/stop the command ---------------------------------------------------------------------------------------------- Bash Bang (!) Commands: !! – run the last command !blah – run the most recent command that starts with ‘blah’ (e.g. !ls) !blah:p – print out the command that !blah would run (also adds it as the latest command in the command history) ----------------------------------------------------------------------------------------------

+ cut (Oct. 14, 2021, 7:36 p.m.)

When using the "ls -l" command, there are multiple spaces before the "size" column. This makes "cut" command not work properly. Because the delimiter in "cut" command splits the columns based on "space" characters separately. We have to use "tr" to "translate or delete characters" (based on its "man tr"): ls -l | cut -d ' ' -f 8 (This will not give us the correct column) ls -l | tr -s ' ' | cut -d' ' -f8 (This will fix the problem) --------------------------------------------------------------------

+ Generate an MD5 string or hash (July 2, 2021, 2:01 p.m.)

echo -n 'mohsen' | md5sum OR echo -n 'mohsen' | openssl md5

+ Journal logs (June 15, 2021, 10:35 a.m.)

Query journalctl to find out how much disk space it's consuming: journalctl --disk-usage ------------------------------------------------------------------------ Control the size of this directory using this parameter in your /etc/systemd/journald.conf: SystemMaxUse=50M Restart the logging service: systemctl restart systemd-journald.service ------------------------------------------------------------------------ Retain the most recent data: journalctl --vacuum-size=100M journalctl --vacuum-time=2d ------------------------------------------------------------------------

+ Rotate Images (May 30, 2021, 10:10 p.m.)

for image in *.jpg; do convert "$image" -rotate 90 Mohsen/"$image"; done

+ Run jar files (May 3, 2021, 10:26 p.m.)

java -jar the_file.jar

+ Difference Between Adduser and Useradd? (May 3, 2021, 3:38 p.m.)

- Adduser is the command to add users to the system according to the command line options and configuration information in /etc/adduser.conf. - Useradd is a low-level utility for adding users. -------------------------------------------------------------------------------- - The command adduser creates the user and sets up the account’s home folders and other settings. - The command useradd just creates the user. -------------------------------------------------------------------------------- - The command adduser creates a user directory in the home (/home/user ) automatically. - The command useradd does not create a user directory in the home, if not specified with -m. -------------------------------------------------------------------------------- - The command syntax for adduser is not complicated like in useradd. - The useradd command has some complexity. --------------------------------------------------------------------------------

+ Bash base64 encode and decode (April 27, 2021, 2:43 a.m.)

Encoding text: echo 'mohsen' | base64 ------------------------------------------------------------------ Decoding text: echo 'bW9oc2VuCg==' | base64 --decode ------------------------------------------------------------------ Encoding text file: Print the text in a file as encoded in the command line: base64 a_file.txt ------------------------------------------------------------------ Decoding text file: base64 -d a_decoded_file.txt ------------------------------------------------------------------

+ grep (Jan. 28, 2021, 4:47 p.m.)

grep -wrcn "abcd" --include=*.{js,html} grep -wrciln ".submit" --include=*.{js,html} --exclude=jquery*.js grep -wrciln ".submit" --include=*.{js,html} --exclude=jquery*.js --exclude-dir=ckeditor grep -i 'stop|shutdown' -n, --line-number -R, -r, --recursive -H, --with-filename -h, --no-filename -o, --only-matching / print only what matches the pattern -i, --ignore-case -w, --word-regexp -c, --count --color -l, --files-with-matches -L, --files-without-match --exclude-dir= ------------------------------------------------------------- Find text in a file: grep -A 7 some_word path/to/the/file.log -A NUM, --after-context=NUM Print NUM lines of trailing context after matching lines -B NUM, --before-context=NUM Print NUM lines of leading context before matching lines. -C NUM, -NUM, --context=NUM Print NUM lines of output context. -n, --line-number -H, --with-filename ------------------------------------------------------------- -s supresses errors about unreadable files that may clutter the output -------------------------------------------------------------

+ Disable Bash shell commands history (Dec. 20, 2020, 8:25 a.m.)

Clean command history: history -c ---------------------------------------------------------------- Disable history for a current shell: set +o history Enable the history: set -o history ---------------------------------------------------------------- Permanently disable bash history: echo 'set +o history' >> ~/.bashrc ---------------------------------------------------------------- Clean a history file on a remote host: ssh user@linuxserver "> ~/.bash_history" ---------------------------------------------------------------- Temporarily suspend bash_history on a given shell: unset HISTFILE ----------------------------------------------------------------

+ VimDiff (Nov. 17, 2020, 4:21 p.m.)

]c : - next difference [c : - previous difference do - diff obtain dp - diff put :diffupdate - re-scan the files for differences zr open all folds zm close all folds ----------------------------------------------------------- To avoid whitespace comparison: :set diffopt+=iwhite ----------------------------------------------------------- CTRL+W+W lets you toggle between the diff columns -----------------------------------------------------------

+ Connect to WiFi (Nov. 14, 2020, 11:01 a.m.)

1- Find the WiFi interface using the following command: netstat -i OR ip -s link OR ip link show 2- Edit the file /etc/network/interfaces: auto wlx180f76fa140a iface wlx180f76fa140a inet dhcp wpa-ssid Mohsen-LG-G4 wpa-psk your_password

+ Check open ports (Nov. 10, 2020, 10:08 p.m.)

netstat -tulpn | grep LISTEN ss -tulpn lsof -i -P -n | grep LISTEN

+ Difference between + and \; in find command (Nov. 2, 2020, 9:58 p.m.)

If you use -exec with a plus(+) sign: find . -type f -exec chmod 775 {} + it will be: chmod 775 fileA fileB fileC If you use -exec with a semicolon(;): find . -type f -exec chmod 775 {} \; it will be: chmod 775 fileA chmod 775 fileB chmod 775 fileC

+ Changing file/directory permissions (Oct. 22, 2020, 10:14 a.m.)

Absolute(Numeric) Mode: In this mode, file permissions are not represented as characters but a three-digit octal number. Number Permission Type Symbol 0 No Permission --- 1 Execute --x 2 Write -w- 3 Execute + Write -wx 4 Read r-- 5 Read + Execute r-x 6 Read +Write rw- 7 Read + Write +Execute rwx ------------------------------------------------------------------------- Symbolic Mode In the Absolute mode, you change permissions for all 3 owners. In the symbolic mode, you can modify the permissions of a specific owner. It makes use of mathematical symbols to modify the file permissions: u user/owner g group o other a all chmod o=rwx file_name chmod g+x file_name chmod u-r file_name -------------------------------------------------------------------------

+ ShadowSocks Dockerized (Oct. 21, 2020, 12:24 p.m.)

version: "3.8" services: shadowsocks: image: shadowsocks/shadowsocks-libev container_name: shadowsocks ports: - "8388:8388/tcp" - "8388:8388/udp" environment: - METHOD=chacha20-ietf-poly1305 - PASSWORD=Password restart: always

+ Bind9 Dockerized (Oct. 21, 2020, 2:27 a.m.)

version: "3.8" services: bind9: container_name: bind9 hostname: bind network_mode: bridge image: fffaraz/bindwebmin restart: unless-stopped ports: - "53:53/tcp" - "53:53/udp" - "10000:10000/tcp" volumes: - /root/services/bind/data:/data environment: - WEBMIN_ENABLED=true - ROOT_PASSWORD=M.H.4301

+ SourcesList - Debian/Buster (Oct. 21, 2020, 1:16 a.m.)

deb buster main deb-src buster main deb buster/updates main deb-src buster/updates main deb buster-updates main deb-src buster-updates main

+ SourcesList - Ubuntu (Oct. 17, 2020, 8:12 p.m.)

# deb cdrom:[Kubuntu 19.10 _Eoan Ermine_ - Release amd64 (20191017)]/ eoan main multiverse restricted universe # See for how to upgrade to # newer versions of the distribution. deb focal main restricted # deb-src eoan main restricted ## Major bug fix updates produced after the final release of the ## distribution. deb focal-updates main restricted # deb-src eoan-updates main restricted ## N.B. software from this repository is ENTIRELY UNSUPPORTED by the Ubuntu ## team. Also, please note that software in universe WILL NOT receive any ## review or updates from the Ubuntu security team. deb focal universe # deb-src eoan universe deb focal-updates universe # deb-src eoan-updates universe ## N.B. software from this repository is ENTIRELY UNSUPPORTED by the Ubuntu ## team, and may not be under a free licence. Please satisfy yourself as to ## your rights to use the software. Also, please note that software in ## multiverse WILL NOT receive any review or updates from the Ubuntu ## security team. deb focal multiverse # deb-src eoan multiverse deb focal-updates multiverse # deb-src eoan-updates multiverse ## N.B. software from this repository may not have been tested as ## extensively as that contained in the main release, although it includes ## newer versions of some applications which may provide useful features. ## Also, please note that software in backports WILL NOT receive any review ## or updates from the Ubuntu security team. deb focal-backports main restricted universe multiverse # deb-src eoan-backports main restricted universe multiverse ## Uncomment the following two lines to add software from Canonical's ## 'partner' repository. ## This software is not part of Ubuntu, but is offered by Canonical and the ## respective vendors as a service to Ubuntu users. # deb eoan partner # deb-src eoan partner deb focal-security main restricted # deb-src eoan-security main restricted deb focal-security universe # deb-src eoan-security universe deb focal-security multiverse # deb-src eoan-security multiverse # This system was installed using small removable media # (e.g. netinst, live or single CD). The matching "deb cdrom" # entries were disabled at the end of the installation process. # For information about how to configure apt package sources, # see the sources.list(5) manual. # deb [arch=amd64] focal contrib deb [arch=amd64] focal stable # deb-src [arch=amd64] focal stable

+ Mercurial (Oct. 8, 2020, 11:55 a.m.) ------------------------------------------------------------------------ Installation: apt install mercurial ------------------------------------------------------------------------ Set the username that Mercurial will use for commits: vim ~/.hgrc [ui] username = Mohsen Hassani <> ignore = /home/mohsen/.hg/.hgignore ------------------------------------------------------------------------ vim ~/.hgignore syntax: regexp ^\.idea ------------------------------------------------------------------------ Add the project to Mercurial: hg commit -A -m 'Commit with automatic autoremove'. Commit: hg commit -m "Create new project" ------------------------------------------------------------------------ hg init hg clone hg clone project project-work hg sum hg status hg commit -A -m 'A commit message.' hg merge hg parents # see the revisions that have been merged into the working directory hg export tip # display the full details of the most recent commit hg log hg diff hg revert ------------------------------------------------------------------------ When renaming files, Mercurial will report them as missing (hg status). You can use the following command to automatically add the new files and remove the deleted ones. hg addremove ------------------------------------------------------------------------ hg status hg summ hg shelve hg update trunk hg diff hg revert file_name hg bookmark a_name hg bookmarks hg log -G ------------------------------------------------------------------------ hg summ hg bookmark a_name hg summ hg status hg add # Will add all untracked files, (files with ? in front of the output of hg status) hg commit -m 'A message.' hg push -B a_bookmark_name ------------------------------------------------------------------------ Temporarily stash away changes: hg shelve List all existing shelves: hg shelve --list Get the changes back into the working directory: hg unshelve Shelves can be given custom names (the default name is your active bookmark or branch): hg shelve --name <name> hg unshelve <name> Delete a shelve: hg shelve -d my-shelve ------------------------------------------------------------------------ Rename a bookmark: hg bookmark --rename current-name new-name ------------------------------------------------------------------------ Delete a bookmark: hg bookmark --delete <bookmark name> hg push --bookmark <bookmark name> ------------------------------------------------------------------------ Show the tip revision of the repository graph: hg tip Show the parent revision of the working dir: hg parent ------------------------------------------------------------------------ Print Current Mercurial Revision Hash: hg id -i hg --debug id -i ------------------------------------------------------------------------ Delete by revision hash: Add "strip" extension to the ~/.hgrc file: [extensions] strip = hg strip <hash> ------------------------------------------------------------------------ Undo an uncommitted merge: hg update -C -r . OR hg update --clean ------------------------------------------------------------------------ See changes of the last commit: hg diff -c <hash> Diff between two commits: hg diff -r <rev> -r <rev> ------------------------------------------------------------------------ When doing "hg up trunk", getting this error: abort: outstanding uncommitted merge For fixing the problem: hg update --clean -r tip ------------------------------------------------------------------------ For rebasing: hg rebase --keep -s a2398ed78ba8 -d ec97280fd324 -s which bookmark is rebasing -d which bookmark to be based on ------------------------------------------------------------------------ To abort rebase: hg rebase --abort ------------------------------------------------------------------------ To see the commits of a user: hg log -G --user mohsen ------------------------------------------------------------------------ Find a hash: hg bookmarks | grep trunk ------------------------------------------------------------------------ The status of files: M = modified A = added R = removed C = clean ! = missing (deleted by non-hg command, but still tracked) ? = not tracked I = ignored = origin of the previous file (with --copies) ------------------------------------------------------------------------

+ Control Groups - CGroups (Oct. 7, 2020, 12:20 p.m.)

Cgroups allow you to allocate resources — such as CPU time, system memory, network bandwidth, or combinations of these resources — among user-defined groups of tasks (processes) running on a system.

+ Run commands without sudo (Sept. 21, 2020, 2:50 p.m.)

sudo gpasswd -a $USER docker

+ apt vs apt-get (July 25, 2020, 9:37 a.m.)

apt-get may be considered as lower-level and "back-end", and support other APT-based tools. apt is designed for end-users (human) and its output may be changed between versions. -------------------------------------------------------------------------- Install package: apt-get install apt install -------------------------------------------------------------------------- Remove package: apt-get remove apt remove -------------------------------------------------------------------------- Update all package: apt-get upgrade apt upgrade -------------------------------------------------------------------------- Update all package: apt-get upgrade apt upgrade -------------------------------------------------------------------------- Update all packages (auto handling of dependencies): apt-get dist-upgrade apt full-upgrade -------------------------------------------------------------------------- Search packages: apt-cache search apt search -------------------------------------------------------------------------- Show package information: apt-cache show apt show -------------------------------------------------------------------------- Remove unwanted dependencies: apt-get autoremove apt autoremove -------------------------------------------------------------------------- Removes package with associated configuration: apt-get purge apt purge -------------------------------------------------------------------------- Two new commands introduced with the apt: apt list: When apt list command is used with --installed or --upgradeable, it lists the packages that are installed, available to install, or those that need to be upgraded. apt edit-sources: When this command is used, it opens the "sources.list" file in an editor for editing. -------------------------------------------------------------------------- DIFFERENCES TO APT-GET(8) The apt command is meant to be pleasant for end-users and does not need to be backward compatible like apt-get(8). Therefore some options are different: · The option DPkg::Progress-Fancy is enabled. · The option APT::Color is enabled. · A new list command is available similar to dpkg --list. · The option upgrade has --with-new-pkgs enabled by default. --------------------------------------------------------------------------

+ HTTP Proxy To Socks (July 15, 2020, 10:14 a.m.)

1- Install NodeJS and NPM using my notes. 2- Install http-proxy-to-socks npm install -g http-proxy-to-socks 3- Usage: hpts -s -p 8080

+ Curl (June 29, 2020, 6:32 p.m.)

HTTP GET request curl ---------------------------------------------------------------- Adding an additional HTTP request header: curl -H "X-Header: value" ---------------------------------------------------------------- Storing HTTP headers With the -D option, you have the ability to store the HTTP headers that a site sends back. This is useful for instance if you want to read the cookies from the headers by using a second curl command and including the -b option. The - after the -D tells curl that the output file is stdout (the file into which kernel writes its output). curl -D - ---------------------------------------------------------------- Downloading a file (Saving the result of a curl command): curl -O # Save as yourfile.tar.gz curl -o newfile.tar.gz # Save as newfile.tar.gz ---------------------------------------------------------------- Resume an interrupted Download: curl -C - -O ---------------------------------------------------------------- Download Multiple Files: curl -O -O ---------------------------------------------------------------- Download URLs From a File: xargs -n 1 curl -O < listurls.txt ---------------------------------------------------------------- Use a Proxy with or without Authentication: curl -x -U user:password -O where you can skip -U user:password if your proxy does not require authentication. ---------------------------------------------------------------- Query HTTP Headers: curl -I HTTP headers allow the remote web server to send additional information about itself along with the actual request. This provides the client with details on how the request is being handled. ---------------------------------------------------------------- Make a POST request with Parameters: The following command will send the firstName and lastName parameters, along with their corresponding values, to curl --data "firstName=John&lastName=Doe" ---------------------------------------------------------------- Download Files from an FTP Server with or without Authentication: curl -u username:password -O ftp://yourftpserver/yourfile.tar.gz where you can skip -u username:password if the FTP server allows anonymous logins. ---------------------------------------------------------------- Upload Files to an FTP server with or without Authentication: curl -u username:password -T mylocalfile.tar.gz ftp://yourftpserver ---------------------------------------------------------------- Specify User Agent: The user agent is part of the information that is sent along with an HTTP request. This indicates which browser the client used to make the request. curl -I http://localhost --user-agent "I am a new web browser" OR curl -A "Mozilla/5.0 (X11; Linux x86_64; rv:60.0) Gecko/20100101 Firefox/60.0" ---------------------------------------------------------------- Store Website Cookies: Want to see which cookies are downloaded to your computer when you browse to Use the following command to save them to cnncookies.txt. curl --cookie-jar cnncookies.txt -O ---------------------------------------------------------------- Send Website Cookies: curl --cookie cnncookies.txt ---------------------------------------------------------------- Modify Name Resolution: If you’re a web developer and want to test a local version of before pushing it live, you can make curl resolve to your localhost like so: curl --resolve Thus, the query to will tell curl to request the site from localhost instead of using DNS or the /etc/hosts file. ---------------------------------------------------------------- Limit Download Rate: To prevent curl from hosing your bandwidth, you can limit the download rate to 100 KB/s as follows. curl --limit-rate 100K -O ---------------------------------------------------------------- Follow Redirects: By default, curl doesn’t follow the HTTP Location headers. If you try to retrieve the non-www version of, you will notice that instead of getting the source of the page you’ll be redirected to the www version: curl The -L option instructs curl to follow any redirect until it reaches the final destination: curl -L ---------------------------------------------------------------- Pass HTTP Referer: curl --referer curl --referer fooBar ---------------------------------------------------------------- GET with JSON: curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X GET http://hostname/resource ---------------------------------------------------------------- POST: For posting data: curl --data "param1=value1&param2=value2" http://hostname/resource For file upload: curl --form "fileupload=@filename.txt" http://hostname/resource RESTful HTTP Post: curl -X POST -d @filename http://hostname/resource ----------------------------------------------------------------

+ Password Protect GRUB Bootloader (June 26, 2020, 6:27 p.m.)

1- Issue the following command. You will be prompted to create and verify a password for GRUB grub-mkpasswd-pbkdf2 2- Once that completes, the command will generate a hashed password. We need to add the new hash to 00_header file. Issue the command: vim /etc/grub.d/00_header At the bottom of that file, paste the following: cat << EOF set superusers="admin" password_pbkdf2 admin HASH EOF where HASH is the hash generated earlier. Save and close that file. 3- Update GRUB with the command: update-grub2

+ Shebang (June 22, 2020, 1:02 p.m.)

The shebang is a special character sequence in a script file that specifies which program should be called to run the script. The shebang is always on the first line of the file, and is composed of the characters #! followed by the path to the interpreter program. You can also specify command line options, if necessary. For example, the following line contains the shebang, the path to the Perl interpreter, and the command line option -w: #!/usr/bin/perl -w #!/usr/bin/python #!/usr/bin/python3 #!/usr/bin/env bash

+ scp - Escape spaces (Feb. 20, 2019, 2:58 p.m.)

scp " mhass . ir :/home/mohsen/programs/\[Radio\ Streams\].m3u" Temp/ OR scp -T mhass . ir :/home/mohsen/programs/"\"[Radio Streams].m3u\"" Temp/

+ Delete old kernels (Jan. 12, 2019, 2:57 p.m.)

1- List all installed kernels dpkg -l | grep linux-image | awk '{print$2}' 2- Remove a particular linux-image along with its configuration files: apt remove --purge linux-image-5.0.0-38-generic 3- Remove dependencies: apt autoremove -y 3- Update grub2 configuration: update-grub2

+ Environmental and Shell Variables (Nov. 17, 2018, 2:55 p.m.)

Environmental variables are variables that are defined for the current shell and are inherited by any child shells or processes. Environmental variables are used to pass information into processes that are spawned from the shell. Shell variables are variables that are contained exclusively within the shell in which they were set or defined. They are often used to keep track of ephemeral data, like the current working directory. --------------------------------------------------------------- Printing Shell and Environmental Variables: env OR printenv set | less OR (set -o posix; set) --------------------------------------------------------------- Difference between "env" and "printenv": The difference between the two commands is only apparent in their more specific functionality. For instance, with printenv, you can requests the values of individual variables: printenv SHELL /bin/bash On the other hand, env let's you modify the environment that programs run in by passing a set of variable definitions into a command like this: env VAR1="blahblah" command_to_run command_options --------------------------------------------------------------- Set command: Returns a list of all shell variables, environmental variables, local variables, and shell functions: --------------------------------------------------------------- Setting Shell and Environmental Variables: Specify a name and a value: TEST_VAR='Hello World!' It is a shell variable. This variable is available in our current session, but will not be passed down to child processes. Test it: set | grep TEST_VAR We can verify that this is not an environmental variable by trying the same thing with printenv: printenv | grep TEST_VAR No output should be returned. echo $TEST_VAR --------------------------------------------------------------- Creating Environmental Variables: export TEST_VAR printenv | grep TEST_VAR --------------------------------------------------------------- Change it back environmental variable into a shell variable by typing: export -n TEST_VAR It is no longer an environmental variable: printenv | grep TEST_VAR However, it is still a shell variable: set | grep TEST_VAR If we want to completely unset a variable, either shell or environmental, we can do so with the unset command: unset TEST_VAR We can verify that it is no longer set: echo $TEST_VAR ---------------------------------------------------------------

+ Remote Desktop Clients (Oct. 14, 2018, 3:52 p.m.)

VNC -> Virtual Network Computing RDP -> Remote Desktop Protocol ---------------------------------------------------------------- RDP is used to connect to Windows-based computers VNC is used to connect to Linux machines ----------------------------------------------------------------

+ Open URL in command line (Oct. 29, 2018, 2:25 p.m.) ------------------------------------------------------------ Linux: xdg-open ------------------------------------------------------------ Unix: wget Wget retrieves the HTML file unlike the browser; it only downloads the file without rendering. curl -------------------------------------------------------------

+ Bropages (June 7, 2020, 2:42 p.m.)

The slogan of this utility is "just get to the point". 1- apt install build-essential ruby-dev 2- gem install bropages ----------------------------------------------------------- Fedora: dnf -y install gcc-c++ ruby-devel ----------------------------------------------------------- Usage: bro find This will display a big list/help of usages of "find" command. -----------------------------------------------------------

+ Firefox - Fixing PDFs opening in GIMP (Sept. 28, 2018, 3:30 p.m.)

Open the file: vim /usr/share/applications/mimeinfo.cache Change the line: application/pdf=gimp.desktop;okularApplication_pdf.desktop; To: application/pdf=okularApplication_pdf.desktop;

+ inxi - System Information Tool (July 17, 2018, 2:27 p.m.)

inxi: will produce output to do with system CPU, kernel, uptime, memory size, hard disk size, number of processes, the client used, and inxi version. ---------------------------------------------------------- Show Linux Kernel and Distribution Info: inxi -S Monitor Linux CPU Temperature and Fan Speed: inxi -s ---------------------------------------------------------- Find Linux Laptop or PC Model Information: inxi -M ---------------------------------------------------------- Find Linux CPU and CPU Speed Information inxi -C ---------------------------------------------------------- Show advanced network card information including interface, speed, mac id, state, IPs, etc: inxi -Nni ---------------------------------------------------------- View a distro repository data: inxi -r ---------------------------------------------------------- View whether info: inxi -w inxi -w Tehran,Iran ---------------------------------------------------------- Top 10 most active processes eating up CPU and memory: inxi -t cm10 ---------------------------------------------------------- Linux Hard Disk Partition Details inxi -p ---------------------------------------------------------- Full Linux System Information: inxi -F ---------------------------------------------------------- Linux Processes Memory Usage: inxi -I ---------------------------------------------------------- Audio/Sound Card Information: inxi -A ----------------------------------------------------------

+ List all enabled services from systemctl (June 25, 2018, 2:27 p.m.)

systemctl list-unit-files --state=enabled

+ LZMA (May 16, 2018, 2:26 p.m.)

Note that lzma and xz both use the same compression algorithm, in fact, lzma is deprecated in favor of the newer xz. So you would be better off using xz (tar -J): tar -cpJf backboxhome.tar.xz /home/user Lzma stands for Lempel-Ziv-Markov chain Algorithm. Lzma is a compression tool like bzip2 and gzip to compress and decompress files. It tends to be significantly faster and efficient than bzip compression. As we know, gzip compression ratio is worse than bzip2 (and lzma). lzma -c9 --stdout debian-9.qcow2 > debian.lzma

+ Get the absolute directory of a file in bash (May 15, 2018, 2:24 p.m.)

readlink -f <file_name> -------------------------------------------------------- realpath <file_name> --------------------------------------------------------

+ Sort (May 13, 2018, 2:23 p.m.)

Sort by file size: ls -lh | sort -h -rk5 ------------------------------------------------------- Sort du output in Human-readable format: du -shx * | sort -rh ------------------------------------------------------- -b, --ignore-leading-blanks Ignore leading blanks -d, --dictionary-order Consider only blanks and alphanumeric characters. -f, --ignore-case Fold lower case to upper case characters. -g, --general-numeric-sort Compare according to general numerical value. -i, --ignore-nonprinting Consider only printable characters. -M, --month-sort Compare (unknown) < `JAN' < ... < `DEC'. -h, --human-numeric-sort Compare human-readable numbers (e.g., "2K", "1G"). -n, --numeric-sort Compare according to string numerical value. -R, --random-sort Sort by random hash of keys. --random-source=FILE Get random bytes from FILE. -r, --reverse Reverse the result of comparisons. --sort=WORD Sort according to WORD: general-numeric -g, human-numeric -h, month -M, numeric -n, random -R, version -V. -V, --version-sort Natural sort of (version) numbers within text. -c, --check, --check=diagnose-first Check for sorted input; do not sort. -C, --check=quiet, --check=silent Like -c, but do not report first bad line. -k, --key=POS1[,POS2] Start a key at POS1 (origin 1), end it at POS2 (default end of line). See POS syntax below. -o, --output=FILE Write result to FILE instead of standard output. -t, --field-separator=SEP Use SEP instead of non-blank to blank transition. -z, --zero-terminated End lines with 0 byte, not newline. ------------------------------------------------------- sort -k2 test.txt Sort according to the characters starting at the second column. k2 refers to the second column. ------------------------------------------------------- The -r option reverses the sorting sort -k2 -r test.txt ------------------------------------------------------- Sorting a Stream Output: ls -al | sort -r -n -k5 The -n operator specifies numeric sorting rather than alphabetic. ------------------------------------------------------- sort -k 2n sort -nk2 lsl.txt ------------------------------------------------------- The -k m,n option lets you sort on a key that is potentially composed of multiple fields (start at column m, end at column n): sort -k2n,2 -k1,1 quota sort -k 3.3,3.5 data.txt ------------------------------------------------------- join <(sort file1.txt) <(sort file2.txt) ------------------------------------------------------- ls -l /home/$USER | sort -t "," -nk2,5 -k9 ------------------------------------------------------- sort -u lsl.txt lsla.txt -------------------------------------------------------

+ Find process ID (PID) (May 1, 2018, 2:23 p.m.)

pgrep ^firefox

+ ssh-keygen with name (April 28, 2018, 2:22 p.m.)

ssh-keygen -t rsa -f my_backups

+ Mount mdf image (April 24, 2018, 2:21 p.m.)

1- apt install mdf2iso 2- mount -o loop -t iso9660 file.mdf /mnt/mdf -------------------------------------------------------- You can also try the software acetoneiso which is basically some sort of Daemon Tools / Alcohol 120% for Linux. --------------------------------------------------------

+ gzip, gunzip, zcat (May 21, 2018, 2:20 p.m.)

gzip reduces the size of the named files using Lempel-Ziv coding (LZ77). Whenever possible, each file is replaced by one with the extension .gz, while keeping the same ownership modes, access, and modification times. (The default extension is -gz for VMS, z for MSDOS, OS/2 FAT, Windows NT FAT and Atari.) If no files are specified, or if a file name is "-", the standard input is compressed to the standard output. gzip will only attempt to compress regular files. In particular, it will ignore symbolic links. If the compressed file name is too long for its file system, gzip truncates it. gzip attempts to truncate only the parts of the file name longer than 3 characters. (A part is delimited by dots.) If the name consists of small parts only, the longest parts are truncated. For example, if file names are limited to 14 characters, gzip.msdos.exe is compressed to Names are not truncated on systems which do not have a limit on file name length. By default, gzip keeps the original file name and timestamp in the compressed file. These are used when decompressing the file with the -N option. This is useful when the compressed file name was truncated or when the time stamp was not preserved after a file transfer. Compressed files can be restored to their original form using gzip -d or gunzip or zcat. If the original name saved in the compressed file is not suitable for its file system, a new name is constructed from the original one to make it legal. ------------------------------------------------------------ gunzip takes a list of files on its command line and replaces each file whose name ends with .gz, -gz, .z, -z, or _z (ignoring case) and which begins with the correct magic number with an uncompressed file without the original extension. gunzip also recognizes the special extensions .tgz and .taz as shorthands for .tar.gz and .tar.Z respectively. When compressing, gzip uses the .tgz extension if necessary instead of truncating a file with a .tar extension. gunzip can currently decompress files created by gzip, zip, compress, compress -H or pack. The detection of the input format is automatic. ------------------------------------------------------------ zcat is identical to gunzip -c. (On some systems, zcat may be installed as gzcat to preserve the original link to compress.) zcat uncompresses either a list of files on the command line or its standard input and writes the uncompressed data on standard output. zcat will uncompress files that have the correct magic number whether they have a .gz suffix or not. ------------------------------------------------------------

+ Join Several Partitions Together (May 18, 2018, 2:15 p.m.)

How To Join Several Partition Together To Form a Single Larger One: --------------------------------------------------------------------- 1- apt install mhddfs 2- Create a new mount point directory: mkdir /mnt/virtual.backup 3- Using `mount` command find the `mount point` of each disk you intend to aggregate. mhddfs /mnt/backup1,/mnt/backup2,/mnt/backup3 /mnt/virtual.backup -o allow_other The /mnt/backup{1..3} are the mount points. 4- That's it! Verify the virtual directory using "df -h". Now, update the /etc/fstab file: mhddfs#/mnt/backup1;/mnt/backup2;/mnt/backup3 /mnt/virtual.backup fuse defaults,allow_other 0 0 --------------------------------------------------------------------- For unmounting: umount /mnt/virtual.backup ---------------------------------------------------------------------

+ Crontab - Remove old backup files (June 7, 2020, 9:45 a.m.)

find /var/mohsen_backups/ -type f -name "*.tar.gz" ! -newermt "`date --date='-8 days'`" -exec rm {} +

+ Install WINE on Kubuntu (May 6, 2020, 10:12 a.m.)

dpkg --add-architecture i386 apt-get -y install software-properties-common wget wget -qO - | sudo apt-key add - apt-add-repository 'deb bionic main' add-apt-repository ppa:cybermax-dexter/sdl2-backport apt install --install-recommends winehq-stable

+ Kubuntu - Upgrade (April 26, 2020, 8:35 a.m.)

Test correct version is found: do-release-upgrade -c Upgrade in case the correct version is shown: do-release-upgrade --------------------------------------------------------------------------------- upgrade to the development state: do-release-upgrade -d --------------------------------------------------------------------------------- if you wish to do the entire upgrade in a terminal: do-release-upgrade -m desktop ---------------------------------------------------------------------------------

+ OpenConnect VPN Server (April 24, 2020, 8:33 p.m.) --------------------------------------------------------------- 1- apt install ocserv 2- Check its status: systemctl status ocserv If not started, use the following command to start the service: systemctl start ocserv By default OpenConnect VPN server listens on TCP and UDP port 443. If it’s being used by the web server, then the VPN server can’t be started. (Fix this problem in step 5). 3- Installing Let’s Encrypt Client (Certbot): apt install software-properties-common add-apt-repository ppa:certbot/certbot apt update apt install certbot 4- Obtaining a TLS Certificate from Let’s Encrypt: If there’s no web server running on your Ubuntu 16.04/18.04 server and you want OpenConnect VPN server to use port 443, then you can use the standalone plugin to obtain TLS certificate from Let’s Encrypt. Run the following command. Don’t forget to set A record for your domain name. sudo certbot certonly --standalone --preferred-challenges http --agree-tos --email your-email-address -d 5- If you had a problem in step 2, follow this step. If not, skip this step. If your server has a web-server listening on port 80 and 443, and you want OpenConnect VPN server to use a different port, then it’s a good idea to use the webroot plugin to obtain a certificate because the webroot plugin works with pretty much every web server and we don’t need to install the certificate in the web server. First, you need to create a virtual host for Nginx If you are using Nginx, then sudo nano /etc/nginx/conf.d/ Paste the following lines into the file. server { listen 80; server_name; root /var/www/; location ~ /.well-known/acme-challenge { allow all; } } Save and close the file. Then create the web root directory. sudo mkdir -p /var/www/ Set www-data (Nginx user) as the owner of the web root. sudo chown www-data:www-data /var/www/ -R Reload Nginx for the changes to take effect. sudo systemctl reload nginx Once virtual host is created and enabled, run the following command to obtain Let’s Encrypt certificate using webroot plugin. sudo certbot certonly --webroot --agree-tos --email your-email-address -d -w /var/www/ 6- Editing OpenConnect VPN Server Configuration File: vim /etc/ocserv/ocserv.conf Comment the line: auth = "pam[gid-min=1000]" Uncomment and edit two lines below it, to: auth = "plain[passwd=./ocpasswd]" server-cert = /etc/letsencrypt/csr/0000_csr-certbot.pem server-key = /etc/letsencrypt/keys/0000_key-certbot.pem try-mtu-discovery = true default-domain = ipv4-network = tunnel-all-dns = true dns = Comment out all the route parameters: route = route = route = fef4:db8:1000:1001::/64 no-route = Save and close the file Then restart the VPN server for the changes to take effect. systemctl restart ocserv 7- Fixing DTLS Handshake Failure: cp /lib/systemd/system/ocserv.service /etc/systemd/system/ocserv.service vim /etc/systemd/system/ocserv.service Comment out the following two lines: Requires=ocserv.socket Also=ocserv.socket Save and close the file. Then reload systemd: systemctl daemon-reload Stop ocserv.socket and disable it: systemctl stop ocserv.socket systemctl disable ocserv.socket Restart ocserv service: systemctl restart ocserv.service Check the status: systemctl status ocserv 8- Creating VPN Accounts using the ocpasswd tool: ocpasswd -c /etc/ocserv/ocpasswd mohsen

+ iptables (April 23, 2020, 7:32 p.m.)

Delete prerouting rule: 1- List NAT rules: iptables -t nat -v -L -n --line-number 2- Delete a NAT rule: iptables -t nat -D POSTROUTING 1 -------------------------------------------------------------------

+ PPTP / L2TP - Descriptions (April 17, 2020, 9:42 a.m.)

PPTP or Point-to-Point Tunneling Protocol is an outdated method for implementing VPNs. It is developed by Microsoft and the easiest protocol to configure. PPTP VPN has low overhead and that makes it faster than other VPN protocols. PPTP VPN encrypts data using 128-bit encryption which makes it the fastest but the weakest in terms of security. When you use a VPN connection, it usually affects your Internet speeds due to the encryption process. However, you don’t have to worry about that when using a PPTP VPN because of its low-level encryption. ---------------------------------------------------------------------- L2TP or Layer 2 Tunneling Protocol (L2TP) is the result of a partnership between Cisco and Microsoft. It was created to provide a more secure VPN protocol than PPTP. L2TP is a tunneling protocol like PPTP that allows users to access the common network remotely. L2TP VPN is a combined protocol that has all the features of PPTP, but runs over a faster transport protocol (UDP) thus making it more firewall-friendly. It encrypts data using 256-bit encryption and therefore uses more CPU resources than PPTP. However, the increased overhead required to manage this security protocol makes it perform slower than PPTP. ----------------------------------------------------------------------

+ Limit network bandwidth (March 11, 2020, 8:13 a.m.)

apt install wondershaper wondershaper eth1 256 128 wondershaper clear eth1 --------------------------------------------------------------------

+ Enable /etc/rc.local (March 9, 2020, 9:32 a.m.)

1- Create the following file: vim /etc/systemd/system/rc-local.service 2- Add the following content to it: [Unit] Description=/etc/rc.local Compatibility ConditionPathExists=/etc/rc.local [Service] Type=forking ExecStart=/etc/rc.local start TimeoutSec=0 StandardOutput=tty RemainAfterExit=yes SysVStartPriority=99 [Install] 3- Create the rc.local file: printf '%s\n' '#!/bin/bash' 'exit 0' | sudo tee -a /etc/rc.local 4- Then add execute permission to /etc/rc.local file: chmod +x /etc/rc.local 5- Enable and start the service on system boot: systemctl enable rc-local systemctl start rc-local

+ Command History (Feb. 24, 2020, 9:51 a.m.)

history n Shows the stuff typed – add a number to limit the last n items ---------------------------------------------------------------------- Ctrl + r Interactively search through previously typed commands ---------------------------------------------------------------------- ![value] Execute the last command typed that starts with ‘value’ ---------------------------------------------------------------------- ![value]:p Print to the console the last command typed that starts with ‘value’ ---------------------------------------------------------------------- !! Execute the last command typed ---------------------------------------------------------------------- !!:p Print to the console the last command typed ----------------------------------------------------------------------

+ Chaining Commands (Feb. 24, 2020, 9:46 a.m.)

commandA; commandB Run command A and then B, regardless of the success of A ---------------------------------------------------------------------- commandA && commandB Run command B if A succeeded ---------------------------------------------------------------------- commandA || commandB Run command B if A failed ---------------------------------------------------------------------- commandA Run command A in background ----------------------------------------------------------------------

+ Terminal Shortcuts (Feb. 24, 2020, 9:23 a.m.)

Controlling the Screen: Ctrl+S: Stop all output to the screen. This is particularly useful when running commands with a lot of long, verbose output, but you don’t want to stop the command itself with Ctrl+C. Ctrl+Q: Resume output to the screen after stopping it with Ctrl+S -------------------------------------------------------------------------------- Moving the Cursor: Ctrl+A or Home: Go to the beginning of the line. Ctrl+E or End: Go to the end of the line. Alt+B: Go left (back) one word. Ctrl+B: Go left (back) one character. Alt+F: Go right (forward) one word. Ctrl+F: Go right (forward) one character. Ctrl+XX: Move between the beginning of the line and the current position of the cursor. This allows you to press Ctrl+XX to return to the start of the line, change something, and then press Ctrl+XX to go back to your original cursor position. To use this shortcut, hold the Ctrl key and tap the X key twice. -------------------------------------------------------------------------------- Deleting Text: Ctrl+D or Delete: Delete the character under the cursor. Alt+D: Delete all characters after the cursor on the current line. Ctrl+H or Backspace: Delete the character before the cursor. -------------------------------------------------------------------------------- Fixing Typos: Alt+T: Swap the current word with the previous word. Ctrl+T: Swap the last two characters before the cursor with each other. You can use this to quickly fix typos when you type two characters in the wrong order. Ctrl+_: Undo your last keypress. You can repeat this to undo multiple times. -------------------------------------------------------------------------------- Cutting and Pasting: Ctrl+W: Cut the word before the cursor, adding it to the clipboard. Ctrl+K: Cut the part of the line after the cursor, adding it to the clipboard. Ctrl+U: Cut the part of the line before the cursor, adding it to the clipboard. Ctrl+Y: Paste the last thing you cut from the clipboard. The y here stands for “yank”. -------------------------------------------------------------------------------- Working With Your Command History: Ctrl+P or Up Arrow: Go to the previous command in the command history. Press the shortcut multiple times to walk back through history. Ctrl+N or Down Arrow: Go to the next command in the command history. Press the shortcut multiple times to walk forward through the history. Alt+R: Revert any changes to a command you’ve pulled from your history if you’ve edited it. Ctrl+R: Recall the last command matching the characters you provide. Press this shortcut and start typing to search your bash history for a command. Ctrl+O: Run a command you found with Ctrl+R. Ctrl+G: Leave history searching mode without running a command. -------------------------------------------------------------------------------- reset Resets the terminal display --------------------------------------------------------------------------------

+ VNC Server (Feb. 5, 2020, 1:43 p.m.)

Try this method first, the second method has been bumped into dark screen problem: 1- Install VNC server on server machine apt install x11vnc 2- Run the GUI or command line x11vnc application/command. 3- Install vnc viewer on the client machine (Windows or Linux) and connect to the IP:port ================== Second Method ================== 1- apt install vnc4server 2- With normal linux user, enter the following command and set a password: $ vncserver 3- vim /etc/vnc.conf $localhost = "no"; $vncStartup = "$ENV{HOME}/.vnc/xstartup"; 4- Create a file in ~/.vnc/xstartup with the following content: vim ~/.vnc/xstartup #!/bin/sh unset SESSION_MANAGER unset DBUS_SESSION_BUS_ADDRESS exec startx -------------------------------------------------- vncserver -kill :1 -------------------------------------------------- vncserver -list :* --------------------------------------------------

+ CUDA (Feb. 4, 2020, 2:05 p.m.) ------------------------------------------------------------------------- wget mv /etc/apt/preferences.d/cuda-repository-pin-600 wget dpkg -i cuda-repo-ubuntu1804-10-2-local-10.2.89-440.33.01_1.0-1_amd64.deb apt-key add /var/cuda-repo-10-2-local-10.2.89-440.33.01/ apt update apt install cuda -------------------------------------------------------------------------

+ Nvidia GPU Drivers for Tensorflow (Feb. 3, 2020, 1:38 p.m.)

1- Download and nvidia machine learning repo package: wget dpkg -i nvidia-machine-learning-repo-ubuntu1804_1.0.0-1_amd64.deb ----------------------------------------------------------------------------- 2- Download nvidia cuda repo package: wget dpkg -i cuda-repo-ubuntu1804_10.2.89-1_amd64.deb -----------------------------------------------------------------------------

+ Test GPU (Feb. 3, 2020, 1 p.m.)

Run google-chrome and navigate to the URL about:gpu. If chrome has figured out how to use OpenGL, you will get extremely detailing information about your GPU. ----------------------------------------------------------------------- cat /proc/driver/nvidia/gpus/*/information ----------------------------------------------------------------------- lspci | grep ' VGA ' | cut -d" " -f 1 ----------------------------------------------------------------------- lspci -v -s $(lspci | grep ' VGA ' | cut -d" " -f 1) ----------------------------------------------------------------------- nvidia-smi --list-gpus nvidia-smi -q -----------------------------------------------------------------------

+ Nvidia Drivers (Feb. 3, 2020, 8:41 a.m.)

1- Enable the non-free repository. vim /etc/apt/sources.list deb buster main non-free 2- Update the repository index files and install nvidia-detect utility: apt update apt install nvidia-detect 3- Detect your Nvidia card model and suggested Nvidia driver: # nvidia-detect 4- As suggested install the recommended driver by the previous step: apt install nvidia-driver 5- Reboot: systemctl reboot ----------------------------------------------------------------- 1- Search and download the driver file from Nvidia website: 2- apt install build-essential linux-headers-`uname -r` 3- bash (The file you downloaded in step 1) -----------------------------------------------------------------

+ Motherboard (Feb. 2, 2020, 9:14 a.m.)

To find your motherboard model, use dmidecode or inxi command: dmidecode -t baseboard | grep -i 'Product' ------------------------------------------------------------------------- apt install inxi inxi -M -------------------------------------------------------------------------

+ VGA / GPU (Feb. 2, 2020, 9:03 a.m.)

Fetch details about graphics unit (vga card or video card) lspci -vnn | grep VGA -A 12 ------------------------------------------------------------------------- apt install lshw lshw -numeric -C display lshw -class display lshw -short | grep -i --color display -------------------------------------------------------------------------

+ eyeD3 (Jan. 10, 2020, 5:23 p.m.)

eyeD3 is a Python tool for working with audio files, specifically MP3 files containing ID3 metadata. It provides a command-line tool (eyeD3) and a Python library (import eyed3) that can be used to write your own applications or plugins that are callable from the command-line tool. ---------------------------------------------------------------- It's better to use a virtualenv for installing eyeD3 and its plugins (if you need any): create and activate a virtualenv with Python 3, then install eyeD3 and its "display" plugin: pip install eyed3[display-plugin] ---------------------------------------------------------------- For example, to set some song information in an mp3 file called song.mp3: $ eyeD3 -a Integrity -A "Humanity Is The Devil" -t "Hollow" -n 2 song.mp3 With this command, we’ve set the artist (-a/--artist), album (-A/--album), title (-t/--title), and track number (-n/--track-num) properties in the ID3 tag of the file. ---------------------------------------------------------------- eyeD3 song.mp3 The same can be accomplished using Python. import eyed3 audiofile = eyed3.load("song.mp3") audiofile.tag.artist = u"Integrity" audiofile.tag.album = u"Humanity Is The Devil" audiofile.tag.album_artist = u"Integrity" audiofile.tag.title = u"Hollow" audiofile.tag.track_num = 2 ---------------------------------------------------------------- Rename mp3 files to their titles and prepend the index number: files=(*.mp3) i=0 for file in "${files[@]}"; do i=$(( i + 1 )) eyeD3 --rename ''"$i"'- $title' $file done ---------------------------------------------------------------- Display title: (you need "display" plugin to be installed") eyeD3 -P display -p %t% eyeD3 -P display -p %title% ----------------------------------------------------------------

+ Watch (Jan. 9, 2020, 11:42 a.m.)

watch -d -n 0.2 du -sh ----------------------------------------------------------------- -d highlights the changes in the command output. ----------------------------------------------------------------- -n, --interval <secs> seconds to wait between updates ----------------------------------------------------------------- -t, --no-title turn off header ----------------------------------------------------------------- Watch & Find: watch 'find . | grep mp4' ----------------------------------------------------------------- watch 'command | othertool | yet-another-tool' -----------------------------------------------------------------

+ Send Remote Commands Via SSH (Jan. 6, 2020, 3:37 p.m.)

ssh 'ls -l' ssh 'ls -l; ps -aux; whoami' ssh -t 'top' The -t flag tells ssh that you'll be interacting with the remote shell. Without the -t flag top will return results after which ssh will log you out of the remote host immediately. With the -t flag, ssh keeps you logged in until you exit the interactive command. The -t flag can be used with most interactive commands, including text editors like pico and vi.

+ Remap keyboard keys (Dec. 22, 2019, 4:13 p.m.)

1- run xev in terminal 2- You need to get the code of the key you intend to switch. So after running xev press the key you want to switch and note the keycode. 3- Suppose you want to change that key with the left shift. So using the following example, get the name of the left shift command: xmodmap -pke | grep -i shift 4- Now you can change the key functionality with the following command: xmodmap -e "keycode 94 = Shift_L" 5- To make this change permanent, you need to put the command in the file .Xmodemap: a) Create the following file: nano ~/.Xmodmap b) Add the following line: keycode 94 = Shift_L c) Create the following file: nano ~/.xinitrc d) Add the following command: xmodmap ~/.Xmodmap ---------------------------------------------------------------------- For the control key, you need to add the following at the beginning and end of the ~/.Xmodmap file: clear control add control = Control_L Control_R ---------------------------------------------------------------------- For Gnome, install and use input-remapper: apt install input-remapper ----------------------------------------------------------------------

+ MkDocs (Nov. 5, 2019, 2:05 p.m.) 1- apt install mkdocs 2- Create new MkDocs project: mkdocs new my_project cd my_project 3- mkdocs serve Open up 4- Building the site: mkdocs build ---------------------------------------------------------------- Change development address: dev_addr: '' ---------------------------------------------------------------- Configuration: ---------------------------------------------------------------- Installing a new theme: ---------------------------------------------------------------- Serve in remote host: mkdocs serve -a ---------------------------------------------------------------- Markdown documentation: 1- Emphasis: _italic_ __bold__ ^^underline^^ ~~strike through~~ ==highlight== `inline code` ==*you* **can** ^^combine^^ `too`== 2- Soft & Hard Line Breaks: Put 2 spaces at the end of a line to force a line break. You can also force a break anywhere using the <br> tag. 3- Lists: * need a blank line above to start a new list + valid bullet symbols + `*`, `-` or '+' - 4 spaces or 1 tab - to indent 1. use *numbers* for ordered * can nest 2. **numbers** can be in order 3. can also nest 1. but it will fix them if not - list item with two paragraphs. anything like this paragraph should be indented by 4 spaces or a tab - you can add blocks too > :memo: > > * list under lists > * under lists 4- Tasks: - [ ] Task Lists `- [ ]` - [x] x instead of space - [x] will mark it complete - [ ] work just like lists * can can contain indents * or anything else a list can 1. Or can be nested under others lists - [ ] like this - [ ] and this 2. This can help - [ ] like this - [ ] and this 5- Links: [simple link]( ) [with optional title]( "Google's Homepage") point to a [relative file or md](./embedding/ or mail link with emoji [📧]( or click this cloud icon to see the list of icon options [_cloud_{.icon}]( or [use an image ![](images/dingus/image-small.png)](images/dingus/image.png) [Reference-Style Links][some reference id] put link at bottom of paragraph or page. you can use numbers or text for [reference-style link definitions][1] or leave it empty and just use the [link text itself] to [open in new tab]({.new-tab} use `{target=_blank} or {.new-tab}` attributes use it on [ref links][new tab]{.new-tab} too Indenting _reference links_ 2 spaces is not required but a recommended convention [some reference id]: [1]: [link text itself]: ./images/material.png [new tab]: 6- Images: inline ![](images/dingus/image-small.png) with alt text ![foo](images/dingus/image-small.png) with ref links ![img-small][] can use [sizing attributes](blocks/#sizing-alignment) Put `zoomify` in the alt text bracket to enable clicking to zoom. Try clicking on any of these images ![zoomify][img-dingus]{.tiny} ![zoomify](images/dingus/image.png){.center .xsmall} > :camera: **Figure Title** > ![zoomify](images/dingus/image.png){.center .small} [img-small]: ./images/dingus/image-small.png [img-dingus]: ./images/dingus/image.png 7- Abbreviations: here are some abbr's HTML and FUBAR >:bulb: if your editor gets confused by not having and enclosing * then just add it to end of abbr def. --- >:warning: Don't indent these, doesn't seem to work *[abbr]: Abbreviations *[def]: Definition *[HTML]: Hyper Text Markup Language *[FUBAR]: You know what it means* 8- Footnotes: Footnotes[^1] work like reference links They auto-number like ordered lists[^3] You can use any reference id[^text reference] like ref links they can be organized at bottom of paragraph or page. [^1]: footnote, click the return icon here to go back -> [^3]: the number will not necessarily be what you use [^text reference]: text reference 9- Tables: Colons can be used to align columns. 3 dashes min to separate headers. Outer pipes (|) are optional, and you don't need to make the raw Markdown line up prettily. You can also use inline Markdown. | Tables | Are | Cool | | -------- |:-------------:| ---------:| | col 3 is | right-aligned | $1600 | | col 2 is | centered | $12 | | | **Total** | **$1612** | ==Table== | **Format** | 👀 _scramble_ --- | --- | --- *Still* | `renders` | **nicely** [with links](images/dingus/image-small.png) | images ![zoomify](images/dingus/image-small.png){.tiny} | emojis 🍔 icons _cloud_{.icon} | footnotes[^1] | use `<br>` <br> for multi-line <br> line breaks Colons can be used to align columns. 3 dashes min to separate headers. Outer pipes (|) are optional, and you don't need to make the raw Markdown line up prettily. You can also use inline Markdown. Tables Are Cool col 3 is right-aligned $1600 col 2 is centered $12 Total $1612 Table 10- Blockquotes: > Blockquotes are handy to callout text. they are greedy and will keep grabbing text. The '>' is optional unless trying join > paragraphs, tables etc. a blank line and a new paragraph or other markdown thing end them >:bulb: use a `---` seperator or `<br>` if you want multiple sepearte block quotes --- > can have nested > > blockquotes inside of block quotes block quotes can also contain any valid markdown 11- Blocks - admonitions, callouts, sidebars: > :memo: **Memo Admonition** use blockquotes with emoji indicators for admonition memos, callout etc.. --- > :boom: Title title like above is optional --- > :bulb: See [the section about blocks]( for the list of emojis that can be used. 12- Row Divs: <div markdown="1" class="two-column"> 13- Headings & Breaks: # h1 Heading ## h2 Heading ### h3 Heading #### h4 Heading Horizontal Rules --- ---------------------------------------------------------------- Material Design: pip install mkdocs-material Sample Config: # Configuration theme: name: 'material' palette: primary: 'purple' accent: 'purple' feature: tabs: true # Extensions markdown_extensions: - admonition - codehilite: guess_lang: false - toc: permalink: true ---------------------------------------------------------------- Deployment: mkdocs build A folder named "site" will be created. Zip and scp it to the server and serve it using Nginx or any other web servers. If you don't want the output files to get built in the "site" directory, set another name for site_dir configuration option, in mkdocs.yml file. ----------------------------------------------------------------

+ PPTP VPN Server Setup (Nov. 1, 2019, 6:11 p.m.)

1- Install pptpd and a toolkit to save iptables-rules: apt install pptpd iptables-persistent -y 2- Edit the file /etc/ppp/pptpd-options And comment the following lines: refuse-pap refuse-chap refuse-mschap require-mschap-v2 require-mppe-128 ms-dns ms-dns 3- Add VPN User Accounts: vim /etc/ppp/chap-secrets Add the user and password as follows. Use the tab key to separate them. mohsen pptpd my-password * OR mohsen l2tpd my-password * 4- Allocate Private IP for VPN Server and Clients: vim /etc/pptpd.conf Add the following lines to the end of the file. localip remoteip 5- Enable IP Forwarding: vim /etc/sysctl.conf Add the following line: net.ipv4.ip_forward = 1 sysctl -p 6- Configure Firewall for IP Masquerading: iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE iptables -A POSTROUTING -t nat -o ppp+ -j MASQUERADE # Enable IP forwarding iptables -F FORWARD iptables -A FORWARD -j ACCEPT # Accept GRE packets iptables -A INPUT -p 47 -j ACCEPT iptables -A OUTPUT -p 47 -j ACCEPT # Accept incoming connections to port 1723 (PPTP) iptables -A INPUT -p tcp --dport 1723 -j ACCEPT # Accept all packets via ppp* interfaces (for example, ppp0) iptables -A INPUT -i ppp+ -j ACCEPT iptables -A OUTPUT -o ppp+ -j ACCEPT 7- Save iptables rules for taking activating the VPN on each reboot: iptables-save >/etc/iptables/rules.v4 vim etc/network/if-pre-up.d/iptables-restore-pptp #!/bin/bash /sbin/iptables-restore < /etc/iptables/rules.v4 Save the file. 8- Start pptpd Daemon: service pptpd start service pptpd stop service pptpd restart service pptpd status update-rc.d pptpd enable 9- In order to verify that it is running and listening for incoming connections: netstat -alpn | grep pptp ------------------------------------------------------------------------ Install the following packages on client system: apt install pptp-linux network-manager-pptp In network manager add a PPTP VPN. You will only need the following information: - Gateway: Which is the IP address of your VPN server. - Login: Which is the username in the above chap-secrets file - Password: Which is the password in the above chap-secrets file. ------------------------------------------------------------------------ Get PSK (Pre-shared key): cat /etc/ipsec.d/passwd user:$1$LFUJ14..$j/XsVjDvrLO2ov2sY32Lp1:xauth-psk The (XsVjDvrLO2ov2sY32Lp1) part is PSK. ------------------------------------------------------------------------

+ Network Manager Logs (Nov. 1, 2019, 4:42 p.m.)

journalctl -fu NetworkManager

+ UFW - Uncomplicated Firewall (Oct. 29, 2019, 9:55 a.m.)

The default firewall configuration tool for Ubuntu is ufw. Developed to ease iptables firewall configuration, ufw provides a user friendly way to create an IPv4 or IPv6 host-based firewall. By default UFW is disabled. ------------------------------------------------------------------ ufw enable ufw status verbose ufw show raw ------------------------------------------------------------------ Allow: ufw allow <port>/<optional: protocol> To allow incoming tcp and udp packet on port 53 ufw allow 53 To allow incoming tcp packets on port 53 ufw allow 53/tcp To allow incoming udp packets on port 53 ufw allow 53/udp To allow packets from ufw allow from ufw allow from ufw allow from to any port 22 ufw allow from to any port 22 proto tcp ------------------------------------------------------------------ Deny: ufw deny <port>/<optional: protocol> To deny tcp and udp packets on port 53 ufw deny 53 To deny incoming tcp packets on port 53 ufw deny 53/tcp To deny incoming udp packets on port 53 ufw deny 53/udp Deny by specific IP: ufw deny from ufw deny from to any port 22 ------------------------------------------------------------------ Delete Existing Rule: ufw delete deny 80/tcp ------------------------------------------------------------------ Services: Allow by Service Name: ufw allow <service name> ufw allow ssh Deny by Service Name: ufw deny <service name> ufw deny ssh ------------------------------------------------------------------ Status: Checking the status of ufw will tell you if ufw is enabled or disabled and also list the current ufw rules that are applied to your iptables. ufw status ------------------------------------------------------------------ Logging: To enable logging use: ufw logging on To disable logging use: ufw logging off ------------------------------------------------------------------

+ httrack - Web crawler and copier (Oct. 19, 2019, 12:39 a.m.)

1- Installation: apt install httrack 2- Usage: httrack -r2 '-*' '+*mp3' -X0 --update

+ Radio Streaming Apps (Feb. 20, 2019, 9:02 a.m.)

Cantata apt install cantata mpd Favorite List file location: .local/share/data/cantata/mpd/playlists/ ----------------------------------------------------------- Odio apt install snapd snap install odio ----------------------------------------------------------- Lollypop add-apt-repository ppa:gnumdk/lollypop apt update apt install lollypop If not found, maybe it's "lollypop-xenial". Do an apt-cache search lollypop to find the correct name. ----------------------------------------------------------- Guayadeque add-apt-repository ppa:anonbeat/guayadeque apt-get update apt install guayadeque -----------------------------------------------------------

+ CentOS - yum nogpgcheck (July 7, 2019, 8:09 p.m.)

yum --nogpgcheck localinstall packagename.arch.rpm

+ CentOS - EPEL (July 7, 2019, 5:30 p.m.)

Extra Packages for Enterprise Linux (or EPEL) is a Fedora Special Interest Group that creates, maintains, and manages a high quality set of additional packages for Enterprise Linux, including, but not limited to, Red Hat Enterprise Linux (RHEL), CentOS and Scientific Linux (SL), Oracle Linux (OL). EPEL packages are usually based on their Fedora counterparts and will never conflict with or replace packages in the base Enterprise Linux distributions. EPEL uses much of the same infrastructure as Fedora, including buildsystem, bugzilla instance, updates manager, mirror manager and more.

+ CentOS - Check version (July 7, 2019, 5:26 p.m.)

rpm -q centos-release

+ SMB (June 26, 2019, 7:57 p.m.)

apt install smbclient ------------------------------------------------------------- List all shares: smbclient -L <IP Address> -U Mohsen Connect to a Disk or other services: smbclient //<IP Address>/<Disk or Service Name> -U Mohsen ------------------------------------------------------------- To copy the file from the local file system to the SMB server: smb: \> put local_file remote_file To copy the file from the SMB server to the local file system: smb: \> get remote_file local_file -------------------------------------------------------------

+ aria2c (April 26, 2018, 9:25 a.m.)

aria2c -d ~/Downloads/ -i ~/Downloads/dl.txt --summary-interval=20 --check-certificate=false -c -x16 -s16 -j1 For limiting speed add: --max-overall-download-limit=1400K ------------------------------------------------------------ Rename after download: out=<name.extension> ------------------------------------------------------------

+ Download dependencies and packages to directory (June 24, 2019, 12:08 p.m.)

1- In server with no Internet: apt-get --print-uris --yes install <my_package_name> | grep ^\' | cut -d\' -f2 > downloads.list 2- Download the links from another server with Internet connection: wget --input-file downloads.list 3- Copy the files to the location /var/cache/apt/archives in destination server. 4- Install the package using apt install.

+ Change/Rename username/group (June 16, 2019, 3:43 p.m.)

usermod -l new-name old-name groupmod -n new-group old-group ------------------------------------------------------------------- If following error occurred: usermod: user tom is currently used by process 123: pkill -u old_name 123 pkill -9 -u old_name -------------------------------------------------------------------

+ rsync (May 5, 2018, 9:56 a.m.)

rsync -civarzhne 'ssh -p 22' --no-g --no-p --delete --force --exclude-from 'fair/rsync' fair --------------------------------------------------------------------------- -c, --checksum: Skip based on checksum, not mod-time & size -i, --itemize-changes: Output a change-summary for all updates -v, --verbose : Verbose (try -vv for more detailed information) -a, --archive : Archive mode -r, --recursive : Recurse into directories -z, --compress : Compress file data during the transfer -h, --human-readable --progress : Output numbers in a human-readable format -n, --dry-run: Perform a trial run with no changes made -P: Same as --partial --progress -e "ssh options" : Specify the remote shell to use --delete : delete files that don't exist on sender (system) --------------------------------------------------------------------------- rsync -varPe 'ssh' --ignore-existing* /home/mohsen/Audio/Music/Unsorted/music/ --------------------------------------------------------------------------- Exclude files and folders: Files: --exclude 'sources.txt' --exclude '*.pyc' Directories: --exclude '/static' --exclude 'abc*' Together: --exclude 'sources.txt' --exclude 'abc*' ---------------------------------------------------------------------------

+ Shadowsocks - Proxy tool (May 13, 2018, 7:55 p.m.)

Server Installation: (Use python 2.7) 1- pip install shadowsocks (You can create a virtualenv if you want.) 2- Create a file /etc/shadowsocks.json: { "server": "[server ip address]", "port_password": { "8381": "Mohsen123", "8382": "Mohsen321", "8383": "MoMo" }, "local_port": 1080, "timeout": 600, "method": "aes-256-cfb" } 3- ssserver --manager-address /var/run/shadowsocks-manager.sock -c /etc/shadowsocks.json start (If you installed shadowsocks in a virtualenv, you need to "activate" it to see the command "ssserver") If you got error like this: AttributeError: /usr/lib/x86_64-linux-gnu/ undefined symbol: EVP_CIPHER_CTX_cleanup Refer to the bottom of this note for solution! If you got these errors: [Errno 98] Address already in use can not bind to manager address Delete the file in: rm /var/run/shadowsocks-manager.sock 4- Open Firewall Port to Shadowsocks Client for each ports defined at the above json file: ufw allow proto tcp to port 8381 comment "Shadowsocks server listen port" Do the same for other ports too, 8382, 8383, etc 5- Automatically Start Shadowsocks Service: put the whole line in step 3 in the file /etc/rc.local --------------------------------------------------------------------- Client Installation: (Linux) 1- pip install shadowsocks (You can create a virtualenv if you want.) 2- Create a file /etc/shadowsocks.json with the exact content from step 2 of "Server Installation". 3- sslocal -c /etc/shadowsocks.json (If you installed shadowsocks in a virtualenv, you need to "activate" it to see the command "sslocal") --------------------------------------------------------------------- Client Installation: (Android) Install the Shadowsocks app from the link below: --------------------------------------------------------------------- If you got error like this: AttributeError: /usr/lib/x86_64-linux-gnu/ undefined symbol: EVP_CIPHER_CTX_cleanup Open the file: vim /usr/local/lib/python2.7/dist-packages/shadowsocks/crypto/ Replace "cleanup" with "reset" in line 52: libcrypto.EVP_CIPHER_CTX_cleanup.argtypes = (c_void_p,) libcrypto.EVP_CIPHER_CTX_reset.argtypes = (c_void_p,) And also replace "cleanup" with "reset" in line 111: libcrypto.EVP_CIPHER_CTX_cleanup with: libcrypto.EVP_CIPHER_CTX_reset ---------------------------------------------------------------------

+ Check if a disk is an SSD or an HDD (Dec. 18, 2018, 7:51 a.m.)

cat /sys/block/sda/queue/rotational You should get the value 0 for an SSD -------------------------------------------------------------- lsblk -d -o name,rota This will return either 0 (for rotational speed false, meaning SSD) or 1 (for rotating drives, meaning non-SSD) -------------------------------------------------------------- Verify VPS provided is on SSD drive: dd if=/dev/zero of=/tmp/basezap.img bs=512 count=1000 oflag=dsync This command should take only a few seconds if it is an SSD. If it took longer, it is a normal hard disk. -------------------------------------------------------------- time for i in `seq 1 1000`; do dd bs=4k if=/dev/sda count=1 skip=$(( $RANDOM * 128 )) >/dev/null 2>&1; done --------------------------------------------------------------

+ ffmpeg (May 10, 2019, 3 p.m.)

Cut Audio & Vide files: ffmpeg -i 1.mp3 -ss 00:11 -t 1:26 -c copy 2.mp3 ffmpeg -i 4.VOB -ss 00:14 -t 02:11 -c copy cut2.mp4 For 3GP files, the following error will raise: Could not find tag for codec amr_nb in stream #1, codec not currently supported in container . To fix it, add "-c:a aac" instead of "copy" ffmpeg -i DSC00053.3GP -ss 00:00 -t 00:25 -c:a aac 12.mp4 --------------------------------------------------------- Resize resolution: ffmpeg -i input.mp4 -s 640x480 -b:v 1024k -vcodec mpeg4 -acodec copy input.mp4 List of all formats & codes supported by ffmpeg: ffmpeg -formats ffmpeg -codecs --------------------------------------------------------- Converting mp4 to mp3: ffmpeg -i video.mp4 -vn -acodec libmp3lame -ac 2 -qscale:a 4 -ar 48000 audio.mp3 --------------------------------------------------------- Merge audio & video: ffmpeg -i video.mp4 -i audio.mp3 -c:v copy -c:a mp3 -strict experimental output.mp4 --------------------------------------------------------- m2t to mp3: ffmpeg -i mohsen.m2t -f mp3 -acodec mp3 -ab 320 -ar 44100 -vn mohsen.mp3 --------------------------------------------------------- Join/Concatenate Audio/Video files: 1- Write the address of the files in a text file: vim a.txt file '/home/mohsen/1.mp3' file '/home/mohsen/2.mp3' file '/home/mohsen/3.mp3' ffmpeg -f concat -safe 0 -i a.txt -c copy 3.mp3 --------------------------------------------------------- Convert 3gp to mp3: ffmpeg -i in.3gp -c:a libmp3lame output.mp3 ---------------------------------------------------------

+ OpenVPN (Nov. 18, 2018, 8:22 a.m.) =================== Server Configuration =================== 1- apt install openvpn easy-rsa 2- make-cadir /var/openvpn-ca 3- Build the Certificate Authority: cd /var/openvpn-ca mv openssl-1.0.0.cnf openssl.cnf source vars ./clean-all ./build-ca 4- Create the Server Certificate, Key, and Encryption Files: ./build-key-server server When asked for "Sign the certificate" reply "y" ./build-dh 5- Generate an HMAC signature to strengthen the server's TLS integrity verification capabilities: openvpn --genkey --secret keys/ta.key 6- Generate a Client Certificate and Key Pair: ./build-key user1 7- Copy the Files to the OpenVPN Directory: cd keys cp ca.crt server.crt server.key ta.key dh2048.pem /etc/openvpn If the file "dh2048.pem" was not available, you can copy it from: cp /usr/share/doc/openvpn/examples/sample-keys/dh2048.pem /etc/openvpn or you might need to locate it. 8- Copy and unzip a sample OpenVPN configuration file into configuration directory: gunzip -c /usr/share/doc/openvpn/examples/sample-config-files/server.conf.gz | tee /etc/openvpn/server.conf 9- Adjust the OpenVPN Configuration: vim /etc/openvpn/server.conf * Find the directive "tls-auth ta.key 0", uncomment it (if it's commented) and add "key-direction 0" below it. * Find "cipher AES-256-CBC", uncomment it and add "auth SHA256" below it. * Find and uncomment: user nobody group nogroup push "redirect-gateway def1 bypass-dhcp" push "dhcp-option DNS" push "dhcp-option DNS" 10- Allow IP Forwarding: Uncomment the line "net.ipv4.ip_forward" in the file "vim /etc/sysctl.conf". To read the file and adjust the values for the current session, type: sysctl -p 11- Adjust the UFW Rules to Masquerade Client Connections: Find the public network interface using: ip route | grep default The part after "dev" is the public network interface. We need it for next step. 12- Add the following lines to the the bottom of the file "/etc/ufw/before.rules": There is a "COMMIT" at the end of the file. Do not delete or comment that "COMMIT". Just add this block at the end of the file. Each "COMMIT" apply their own block rules. # START OPENVPN RULES # NAT table rules *nat :POSTROUTING ACCEPT [0:0] # Allow traffic from OpenVPN client to server public network interface -A POSTROUTING -s -o <your_public_network_interface> -j MASQUERADE COMMIT # END OPENVPN RULES 13- Open the file "/etc/default/ufw": Find "DEFAULT_FORWARD_POLICY="DROP"" and change "DROP" to "ACCEPT". 14- Open the OpenVPN Port and Enable the Changes: ufw allow 1194/udp ufw allow OpenSSH ufw disable ufw enable 15- Start and Enable the OpenVPN Service: systemctl start openvpn@server systemctl status openvpn@server Also check that the OpenVPN tun0 interface is available: ip addr show tun0 16- Enable the service so that it starts automatically at boot: systemctl enable openvpn@server 17- Create the Client Config Directory Structure: mkdir -p /var/client-configs/files chmod 700 /var/client-configs/files 18- Copy an example client configuration: cp /usr/share/doc/openvpn/examples/sample-config-files/client.conf /var/client-configs/base.conf 19- Open the "/var/client-configs/base.conf" file and enter your server IP to the directive: remote <your_server_ip> 1194 Uncomment: user nobody group nogroup Comment: # ca ca.crt # cert client.crt # key client.key Add "auth SHA256" after the line "cipher AES-256-CBC" Add "key-direction 1" somewhere in the file. Add a few commented out lines: # script-security 2 # up /etc/openvpn/update-resolv-conf # down /etc/openvpn/update-resolv-conf If your client is running Linux and has an /etc/openvpn/update-resolv-conf file, you should uncomment these lines from the generated OpenVPN client configuration file. 20- Creating a Configuration Generation Script: vim /var/client-configs/ Paste the following script: #!/bin/bash # First argument: Client identifier KEY_DIR=/var/openvpn-ca/keys OUTPUT_DIR=/var/client-configs/files BASE_CONFIG=/var/client-configs/base.conf cat ${BASE_CONFIG} \ <(echo -e '<ca>') \ ${KEY_DIR}/ca.crt \ <(echo -e '</ca>\n<cert>') \ ${KEY_DIR}/${1}.crt \ <(echo -e '</cert>\n<key>') \ ${KEY_DIR}/${1}.key \ <(echo -e '</key>\n<tls-auth>') \ ${KEY_DIR}/ta.key \ <(echo -e '</tls-auth>') \ > ${OUTPUT_DIR}/${1}.ovpn 21- Mark the file as executable: chmod 700 /var/client-configs/ 22- Generate Client Configurations: cd /var/client-configs/ ./ user1 If everything went well, we should have a "user1.ovpn" file in our "/var/client-configs/files" directory. 23- Transferring Configuration to Client Devices: Use scp or any other methods to download a copy of the create "user1.ovpn" file to your client. =================== Client Configuration =================== 24- Install the Client Configuration: apt install openvpn 25- Check to see if your distribution includes a "/etc/openvpn/update-resolv-conf" script: ls /etc/openvpn If you see a file "update-resolve-conf": Edit the OpenVPN client configuration file you transferred and uncomment the three lines we placed in to adjust the DNS settings. 26- If you are using CentOS, change the group from nogroup to nobody to match the distribution's available groups: 27- Now, you can connect to the VPN by just pointing the openvpn command to the client configuration file: sudo openvpn --config user1.ovpn

+ DVB - TV Card Driver (April 17, 2015, 6:19 p.m.)

This will install the driver automatically: 1- mkdir it9135 && cd it9135 2- wget 3- unzip 4- dd if=dvb-usb-it9135.fw ibs=1 skip=64 count=8128 of=dvb-usb-it9135-01.fw 5- dd if=dvb-usb-it9135.fw ibs=1 skip=12866 count=5817 of=dvb-usb-it9135-02.fw 6- rm dvb-usb-it9135.fw 7- sudo install -D *.fw /lib/firmware 8- sudo chmod 644 /lib/firmware/dvb-usb-it9135* && cd .. && rm -rf it9135 9- sudo apt install kaffeine After the above solution, you should be able to watch Channels via Kaffeine (or any other DVB Players). Just grab Kaffein, scan the frequencies and you should be fine! ------------------------------------------------------------- If you had problems with the above solution, check the older method below: 1- sudo apt-get install libproc-processtable-perl git libc6-dev 2- git clone git:// 3- cd media_build 4- $ ./build 5- sudo make install 6- apt-get install me-tv kaffeine 7- reboot for loading the driver (I don't know the driver for modprobe yet). ----------------------------------------------------- Scan channels using Kaffein: 1- Open Kaffein 2- From `Television` menu, choose `Configure Television`. 3- From `Device 1` tab, from `Source` option, choose `Autoscan` 4- From `Television` menu choose `Channels` 5- Click on `Start Scan` and after the scan procedure is done, select all channels from the side panel and click on `Add Selected` to add them to your channels. ------------------------------------------------------------- The path Kaffeine is using for saving channel files: /home/mohsen/.local/share/kaffeine/ Opening the file "scanfile.dvb" in a text editor, you'll find out in the first line that you can download the latest channels via the below URL: To update the frequency list, download the file "scantable.dvb" from the following URL, rename it to "scanfile.dvb" and copy it to the path "/home/mohsen/.local/share/kaffeine/". -------------------------------------------------------------

+ sed (April 7, 2018, 4:59 p.m.)

sed -i 's/old-text/new-text/g' input.txt ------------------------------------------------------------------------ echo "the old string . . . " | sed -e "s/old/new/g/" ------------------------------------------------------------------------ Remove the first line from the output: $ grep -u mohsen sshd 16600 16792 16875 $ pgrep -u mohsen sshd | sed 1d 16792 16875 ------------------------------------------------------------------------

+ Install GRUB manually (March 9, 2018, 10:35 a.m.)

sudo mount /dev/sdax /mnt sudo mount --bind /dev /mnt/dev sudo mount --bind /dev/pts /mnt/dev/pts sudo mount --bind /proc /mnt/proc sudo mount --bind /sys /mnt/sys sudo chroot /mnt update-initramfs -u update-grub2

+ Forwarding X (March 6, 2018, 6:25 p.m.)

1- Edit the file sshd_config: vim /etc/ssh/sshd_config X11Forwarding yes X11UseLocalhost no 2- Restart ssh server: /etc/init.d/ssh reload 3- Install xauth: apt install xauth 4- SSH to the server: ssh -X

+ Partitioning Error - Partition table entries are not in disk order (Feb. 13, 2018, 4:07 p.m.)

sudo gdisk /dev/sda p (the p-command prints the recent partition-table on-screen) s (the s-command sorts the partition-table entries) p (use the p-command again to see the result on your screen) w (write the changed partition-table to the disk) q (quit gdisk)

+ tcpdump (Jan. 13, 2018, 9:59 a.m.)

apt install tcpdump sudo tcpdump -i any -n host sudo tcpdump -nti any port 80

+ Use cURL on specific interface (Jan. 9, 2018, 11:39 a.m.)

curl -o rootLast.tbz2 --interface eno2

+ PDF Conversions (Nov. 6, 2017, 1:51 p.m.)

Installation: apt install graphicsmagick-imagemagick-compat ------------------------------------------------------------- Convert multiple images to a PDF file: convert *.jpg aa.pdf ------------------------------------------------------------- For a PDF file with 4 pages: for page in {0..3}; do convert pdf_file.pdf[$page] pdf_file_$page.jpg; done ------------------------------------------------------------- Convert a PDF file to images: convert 1.pdf 1.jpg For a single page: convert 1.pdf[4] 1.jpg ------------------------------------------------------------- If the following error occurred: convert: not authorized `1.pdf' @ error/constitute.c/ReadImage/412. convert: no images defined `1.jpg' @ error/convert.c/ConvertImageCommand/3210. Solution: This problems comes from a security update. Edit the file: /etc/ImageMagick-6/policy.xml Change "none" to "read|write" in the line: <policy domain="coder" rights="read|write" pattern="PDF" /> -------------------------------------------------------------

+ Add a new hard disk to an existing Linux server (Oct. 25, 2017, 3:14 p.m.)

1- Check if the added disk is shown: fdisk -l 2- For partitioning: fdisk /dev/vdb n p 1 Choose the default 2048 Choose the default (Max size) w 3- Format the disk with mkfs command. mkfs.ext4 /dev/vdb1 4- Make an entry in /etc/fstab file for permanent mount at boot time: /dev/vdb1 /mnt/ftp ext4 nobootwait,user,rw 0 0

+ Clear Terminal Completely (Sept. 18, 2017, 4:43 p.m.)

clear && printf '\e[3J' OR printf '\33c\e[3J'

+ SSH Key (Sept. 18, 2017, 3:31 p.m.)

ssh-keygen -t rsa ------------------------------------------------------------ Permissions And Ownership: Both the host and the client should have the following permissions and owners: ~/.ssh permissions should be 700 ~/.ssh should be owned by your account ~/.ssh/authorized_keys permissions should be 600 ~/.ssh/authorized_keys should be owned by your account Client environments should additionally have the following permissions and owners: ~/.ssh/config permissions should be 600 ~/.ssh/id_* permissions should be 600 ------------------------------------------------------------ ssh-add .ssh/id_rsa If you got an error: Could not open a connection to your authentication agent. For fixing it run: eval `ssh-agent -s` OR eval $(ssh-agent) And then repeat the earlier command (ssh-add ....) ------------------------------------------------------------ Add SSH private key permanently: Create a file ~/.ssh/config with the content: IdentityFile ~/.ssh/id_mohsen ------------------------------------------------------------

+ Commands - IP (Sept. 16, 2017, 3:59 p.m.)

Assign an IP Address to Specific Interface: ip addr add dev eth1 --------------------------------------------------------------------- Check an IP Address ip addr show --------------------------------------------------------------------- Remove an IP Address ip addr del dev eth1 --------------------------------------------------------------------- Enable Network Interface ip link set eth1 up --------------------------------------------------------------------- Disable Network Interface ip link set eth1 down --------------------------------------------------------------------- Check Route Table ip route show --------------------------------------------------------------------- Add Static Route ip route add via dev eth0 --------------------------------------------------------------------- Remove Static Route ip route del --------------------------------------------------------------------- Add Default Gateway ip route add default via ---------------------------------------------------------------------

+ Commands - Find (Sept. 12, 2017, 9:38 a.m.)

Find Files Using Name in Current Directory find . -name mohsen.txt ---------------------------------------------------------- Find Files Under Home Directory find /home -name mohsen.txt ---------------------------------------------------------- Find Files Using Name and Ignoring Case find /home -iname mohsen.txt ---------------------------------------------------------- Find Directories Using Name find / -type d -name Mohsen ---------------------------------------------------------- Find PHP Files Using Name find . -type f -name mohsen.php ---------------------------------------------------------- Find all PHP Files in Directory find . -type f -name "*.php" ---------------------------------------------------------- Find Files With 777 Permissions find . -type f -perm 0777 -print ---------------------------------------------------------- Find Files Without 777 Permissions find / -type f ! -perm 777 ---------------------------------------------------------- Find SGID Files with 644 Permissions find / -perm 2644 ---------------------------------------------------------- Find Sticky Bit Files with 551 Permissions find / -perm 1551 ---------------------------------------------------------- Find SUID Files find / -perm /u=s ---------------------------------------------------------- Find SGID Files find / -perm /g=s ---------------------------------------------------------- Find Read Only Files find / -perm /u=r ---------------------------------------------------------- Find Executable Files find / -perm /a=x ---------------------------------------------------------- Find Files with 777 Permissions and Chmod to 644 find / -type f -perm 0777 -print -exec chmod 644 {} \; ---------------------------------------------------------- Find Directories with 777 Permissions and Chmod to 755 find / -type d -perm 777 -print -exec chmod 755 {} \; ---------------------------------------------------------- Find and remove single File find . -type f -name "tecmint.txt" -exec rm -f {} \; ---------------------------------------------------------- Find and remove Multiple File find . -type f -name "*.txt" -exec rm -f {} \; OR # find . -type f -name "*.mp3" -exec rm -f {} \; ---------------------------------------------------------- Find all Empty Files find /tmp -type f -empty ---------------------------------------------------------- Find all Empty Directories find /tmp -type d -empty ---------------------------------------------------------- File all Hidden Files find /tmp -type f -name ".*" ---------------------------------------------------------- Find Single File Based on User find / -user root -name mohsen.txt ---------------------------------------------------------- Find all Files Based on User find /home -user mohsen ---------------------------------------------------------- Find all Files Based on Group find /home -group developer ---------------------------------------------------------- Find Particular Files of User find /home -user mohsen -iname "*.txt" ---------------------------------------------------------- Find Last 50 Days Modified Files find / -mtime 50 ---------------------------------------------------------- Find Last 50 Days Accessed Files find / -atime 50 ---------------------------------------------------------- Find Last 50-100 Days Modified Files find / -mtime +50 –mtime -100 ---------------------------------------------------------- Find Changed Files in Last 1 Hour find / -cmin -60 ---------------------------------------------------------- Find Modified Files in Last 1 Hour find / -mmin -60 ---------------------------------------------------------- Find Accessed Files in Last 1 Hour find / -amin -60 ---------------------------------------------------------- Find 50MB Files find / -size 50M ---------------------------------------------------------- Find Size between 50MB – 100MB find / -size +50M -size -100M ---------------------------------------------------------- Find and Delete 100MB Files find / -size +100M -exec rm -rf {} \; ---------------------------------------------------------- Find Specific Files and Delete find / -type f -name *.mp3 -size +10M -exec rm {} \; ---------------------------------------------------------- Find + grep find . -type f -iname "*.py" -exec grep --exclude=./PC-Projects/* -Riwl 'sqlalchemy' {} \; ---------------------------------------------------------- find /var/mohsen_backups -name "*`date --date='-20 days' +%Y-%m-%d`.tar.gz" -exec rm {} + ---------------------------------------------------------- Files created/modified before the date "2019-05-07": find . ! -newermt "2019-05-07" After the date: find . -newermt "2019-05-07" Using datetime: find . ! -newermt "2019-05-07 12:23:17" Also: find . -newermt "june 01, 2019" find . -not -newermt "june 01, 2019" find . -type f ! -newermt "June 01, 2019" -exec rm {} + ---------------------------------------------------------- find . -name "*.mp4" -exec mv {} videos/ \; ----------------------------------------------------------

+ Netstat (Sept. 12, 2017, 9:30 a.m.)

netstat (network statistics) --------------------------------------------------------- netstat -pnult | grep LISTEN --------------------------------------------------------- Listing all the LISTENING Ports of TCP and UDP connections netstat -a --------------------------------------------------------- Listing TCP Ports connections netstat -at --------------------------------------------------------- Listing UDP Ports connections netstat -au --------------------------------------------------------- Listing all LISTENING Connections netstat -l --------------------------------------------------------- Listing all TCP Listening Ports netstat -lt --------------------------------------------------------- Listing all UDP Listening Ports netstat -lu --------------------------------------------------------- Listing all UNIX Listening Ports netstat -lx --------------------------------------------------------- Showing Statistics by Protocol netstat -s --------------------------------------------------------- Showing Statistics by TCP Protocol netstat -st --------------------------------------------------------- Showing Statistics by UDP Protocol netstat -su --------------------------------------------------------- Displaying Service name with PID netstat -tp --------------------------------------------------------- Displaying Promiscuous Mode netstat -ac 5 | grep tcp --------------------------------------------------------- Displaying Kernel IP routing netstat -r --------------------------------------------------------- Showing Network Interface Transactions netstat -i --------------------------------------------------------- Showing Kernel Interface Table netstat -ie --------------------------------------------------------- Displaying IPv4 and IPv6 Information netstat -g --------------------------------------------------------- Print Netstat Information Continuously netstat -c --------------------------------------------------------- Finding non supportive Address netstat --verbose --------------------------------------------------------- Finding Listening Programs netstat -ap | grep http --------------------------------------------------------- Displaying RAW Network Statistics netstat --statistics --raw --------------------------------------------------------- Post the output in numerics: netstat -nl ---------------------------------------------------------

+ Reverse SSH Tunneling (Sept. 10, 2017, 1:38 p.m.)

1- SSH from the destination to the source (with public IP) using the command below: ssh -R 19999:localhost:22 sourceuser@ * port 19999 can be any unused port. 2- Now you can SSH from source to destination through SSH tunneling: ssh localhost -p 19999 3- 3rd party servers can also access through Destination ( Destination ( <- |NAT| <- Source ( <- Bob's server 3.1 From Bob's server: ssh sourceuser@ 3.2 After the successful login to Source: ssh localhost -p 19999 The connection between destination and source must be alive at all time. Tip: you may run a command (e.g. watch, top) on Destination to keep the connection active.

+ Auto Mount Hard Disk using /etc/fstab (Sept. 8, 2017, 6:41 a.m.)

UUID=e6a27fec-b822-4cc1-9f41-ca14655f938c /media/mohsen/4TB-Internal ext4 rw,user,exec 00 -------------------------------------------------------------------------------- To skip errors add "nobootwait": /dev/sdb1 /mnt/ ext4 nobootwait,user,rw 0 2 -------------------------------------------------------------------------------- File System Types: auto vfat - used for FAT partitions ntfs, ntfs-3g - used for ntfs partitions ext4, ext3, ext2, jfs, reiserfs, etc udf,iso9660 - for CD/DVD -------------------------------------------------------------------------------- Common options : sync/async - All I/O to the file system should be done (a)synchronously. auto - The filesystem can be mounted automatically (at boot-up, or when mount is passed the -a option). This is really unnecessary as this is the default action of mount -a anyway. noauto - The filesystem will NOT be automatically mounted at startup, or when mount passed -a. You must explicitly mount the filesystem. dev/nodev - Interpret/Do not interpret character or block special devices on the file system. exec / noexec - Permit/Prevent the execution of binaries from the filesystem. suid/nosuid - Permit/Block the operation of suid, and sgid bits. ro - Mount read-only. rw - Mount read-write. user - Permit any user to mount the filesystem. This automatically implies noexec, nosuid,nodev unless overridden. nouser - Only permit root to mount the filesystem. This is also a default setting. defaults - Use default settings. Equivalent to rw, suid, dev, exec, auto, nouser, async. _netdev - this is a network device, mount it after bringing up the network. Only valid with fstype nfs. --------------------------------------------------------------------------------

+ Crontab (July 10, 2017, 11:25 p.m.)

The crontab (cron derives from chronos, Greek for time; tab stands for table). ---------------------------------------------- To see what crontabs are currently running on your system: sudo crontab -l crontab -u username -l ---------------------------------------------- To edit the list of cronjobs:: sudo crontab -e ---------------------------------------------- To remove or erase all crontab jobs: crontab -r ---------------------------------------------- Running GUI Applications: 0 1 * * * env DISPLAY=:0.0 transmission-gtk Replace :0.0 with your actual DISPLAY. Use "echo $DISPLAY" to find the display. ---------------------------------------------- Cronjobs are written in the following format: * * * * * /bin/execute/this/ As you can see there are 5 stars. The stars represent different date parts in the following order: minute (from 0 to 59) hour (from 0 to 23) day of month (from 1 to 31) month (from 1 to 12) day of week (from 0 to 6) (0=Sunday) ---------------------------------------------- Execute every minute: * * * * * /bin/execute/this/ This means execute /bin/execute/this/ every minute of every hour of every day of the month of every month and every day in the week. ---------------------------------------------- Execute every Friday 1 AM 0 1 * * 5 /bin/execute/this/ ---------------------------------------------- Execute on workdays 1AM 0 1 * * 1-5 /bin/execute/this/ ---------------------------------------------- Execute 10 past after every hour on the 1st of every month 10 * 1 * * /bin/execute/this/ ---------------------------------------------- Run every 10 minutes: 0,10,20,30,40,50 * * * * /bin/execute/this/ But crontab allows you to do this as well: */10 * * * * /bin/execute/this/ ---------------------------------------------- Special words: For the first (minute) field, you can also put in a keyword instead of a number: @reboot Run once, at startup @yearly Run once a year "0 0 1 1 *" @annually (same as @yearly) @monthly Run once a month "0 0 1 * *" @weekly Run once a week "0 0 * * 0" @daily Run once a day "0 0 * * *" @midnight (same as @daily) @hourly Run once an hour "0 * * * *" Leaving the rest of the fields empty, this would be valid: @daily /bin/execute/this/ ---------------------------------------------- List of the English abbreviated day of the week, which can be used in place of numbers: 0 -> Sun 1 -> Mon 2 -> Tue 3 -> Wed 4 -> Thu 5 -> Fri 6 -> Sat 7 -> Sun Having two numbers for Sunday (0 and 7) can be useful for writing weekday ranges starting with 0 or ending with 7. Examples of Number or Abbreviation Use The next four examples will do all the same and execute a command every Friday, Saturday, and Sunday at 9.15 o'clock: 15 09 * * 5,6,0 command 15 09 * * 5,6,7 command 15 09 * * 5-7 command 15 09 * * Fri,Sat,Sun command ---------------------------------------------- Getting output from a cron job on the terminal: You can redirect the output of your program to the pts file of an already existing terminal! To know the pts file just type tty command tty And then add it to the end of your cron task: 38 23 * * * /home/mohsen/Programs/ >> /dev/pts/4 ---------------------------------------------- Cron jobs get logged to: /var/log/syslog You can see just cron jobs in that logfile by running: grep CRON /var/log/syslog OR tail -f /var/log/syslog | grep CRON ---------------------------------------------- Mailing the crontab output By default, cron saves the output in the user's mailbox (root in this case) on the local system. But you can also configure crontab to forward all output to a real email address by starting your crontab with the following line: MAILTO="" Mailing the crontab output of just one cronjob. If you'd rather receive only one cronjob's output in your mail, make sure this package is installed: $ aptitude install mailx And change the cronjob like this: */10 * * * * /bin/execute/this/ 2>&1 | mail -s "Cronjob ouput" ---------------------------------------------- Trashing the crontab output Now that's easy: */10 * * * * /bin/execute/this/ > /dev/null 2>&1 Just pipe all the output to the null device, also known as the black hole. On Unix-like operating systems, /dev/null is a special file that discards all data written to it. ---------------------------------------------- Many scripts are tested in a Bash environment with the PATH variable set. This way it's possible your scripts work in your shell, but when running from cron (where the PATH variable is different), the script cannot find referenced executables and fails. It's not the job of the script to set PATH, it's the responsibility of the caller, so it can help to echo $PATH, and put PATH=<the result> at the top of your cron files (right below MAILTO). ---------------------------------------------- Applicable Examples: 0 * * * DISPLAY=:0 /home/mohsen/Programs/ 0 11 * * * /home/mohsen/Programs/ Do not forget to chomd +x both the following files. ----------- #! /bin/bash /usr/bin/transmission-gtk > /dev/null & echo $! > /tmp/ exit ----------- #! /bin/bash if [ -f /tmp/ ] then /bin/kill $(cat /tmp/ fi ---------------------------------------------- How do I use operators? An operator allows you to specify multiple values in a field. There are three operators: The asterisk (*): This operator specifies all possible values for a field. For example, an asterisk in the hour time field would be equivalent to every hour or an asterisk in the month field would be equivalent to every month. The comma (,) : This operator specifies a list of values, for example: “1,5,10,15,20, 25”. The dash (-): This operator specifies a range of values, for example, “5-15” days, which is equivalent to typing “5,6,7,8,9,….,13,14,15” using the comma operator. The separator (/): This operator specifies a step value, for example: “0-23/” can be used in the hours field to specify command execution every other hour. Steps are also permitted after an asterisk, so if you want to say every two hours, just use */2. ----------------------------------------------

+ fdisk (July 8, 2017, 3:33 p.m.)

Merge Partitions: 1- fdisk /dev/sda 2- p Device Boot Start End Sectors Size Id Type /dev/sda1 * 2048 6293503 6291456 3G 83 Linux /dev/sda2 6295550 10483711 4188162 2G 5 Extended 3- Delete both partitions you are going to merge: d Partition number (1,2, default 2): 2 Partition 2 has been deleted. Command (m for help): d Partition number (1-4): 1 4- n Partition type p primary (1 primary, 0 extended, 3 free) e extended (container for logical partitions) Select (default p): p Partition number (1-4, default 2): 1 First sector (63-1953520064, default: 63): (Choose the default value) Last sector, +sectors... (Choose the default value) 5- t Partition number (1-4): 1 Hex code (type L to list codes): 83 6- Make sure you've got what you're expecting: Command (m for help): p 7- Finally, save it: Command (m for help): w 8- resize2fs /dev/sda1 Reboot the system, then check if the partitions have been merged by: fdisk -l

+ Removing Swap Space (July 8, 2017, 1:22 p.m.)

1- swapoff /dev/sda5 2- Remove its entry from /etc/fstab 3- Remove the partition using parted: apt-get install parted parted /dev/sda Type "print" to view the existing partitions and determine the minor number of the swap partition you wish to delete. rm 5 (5 is the NUMBER of the partition. Type "quit" to exit parted. Done! Now you need to merge the unused partition space with another partition. You can do it using the "fdisk" note.

+ NFS (July 1, 2017, 8:49 a.m.)

NFS (Network File Share) NFS is a network-based file system that allows computers to access files across a computer network. ------------------------------------------------------------------------ Server Setup: 1- Installation: apt install nfs-kernel-server 2- Server Configuration: In order to expose a directory over NFS, open the file /etc/exports and attach the following line at the bottom: /home/mohsen/Audio,async,no_subtree_check) This IP is the client which is going to have access to the shared folder. You can also use the IP range. service nfs-kernel-server restart ------------------------------------------------------------------------ Client Setup 1- Client Installation: apt install nfs-common 2- Create a directory named "Audio" and: mount /mnt/Audio/ By running df -h, you can ensure that your operation was successful. 3- Make it permanent: vim /etc/fstab /mnt/Audio/ nfs _netdev,user,rw 0 0 ------------------------------------------------------------------------ For MacOS use this command: sudo mount -o resvport /mnt/Audio/ ------------------------------------------------------------------------

+ Trim & Merge MP3 files (June 25, 2017, 12:41 p.m.)

sudo apt-get install sox libsox-fmt-mp3 -------------------------------------------------------------------------------- Trim: sox infile outfile trim 0 1:06 sox infile outfile trim 1:52 =2:40 -------------------------------------------------------------------------------- Merge: sox first.mp3 second.mp3 third.mp3 result.mp3 -------------------------------------------------------------------------------- Merge two audio files with a pad: sox short.ogg -p pad 6 0 | sox - -m long.ogg output.ogg --------------------------------------------------------------------------------

+ Fix Wireless Headphone Problem (June 10, 2017, 4:04 p.m.)

+ Convert deb to iso (May 14, 2017, 2:07 p.m.)

mkisofs firmware-bnx2_0.43_all.deb > iso

+ Samba - Active Directory Infrastructure (May 7, 2017, 9:01 a.m.)

1- sudo apt-get install samba krb5-user krb5-config winbind libpam-winbind libnss-winbind 2- While the installation is running a series of questions will be asked by the installer in order to configure the domain controller. First, DESKBIT.LOCAL Second, deskbit.local Third, deskbit.local 3- Provision Samba AD DC for Your Domain: systemctl stop samba-ad-dc.service smbd.service nmbd.service winbind.service systemctl disable samba-ad-dc.service smbd.service nmbd.service winbind.service 4- Rename or remove samba original configuration. This step is absolutely required before provisioning Samba AD because at the provision time Samba will create a new configuration file from scratch and will throw up some errors in case it finds an old smb.conf file. sudo mv /etc/samba/smb.conf /etc/samba/smb.conf.initial 5- Start the domain provisioning interactively: samba-tool domain provision --use-rfc2307 --interactive (Leave everything as default and set a desired password.) Here is the last result after the process gets finished: Server Role: active directory domain controller Hostname: samba NetBIOS Domain: DESKBIT DNS Domain: deskbit.local DOMAIN SID: S-1-5-21-163349405-2119569559-686966403 6- Rename or remove Kerberos main configuration file from /etc directory and replace it using a symlink with Samba newly generated Kerberos file located in /var/lib/samba/private path: mv /etc/krb5.conf /etc/krb5.conf.initial ln -s /var/lib/samba/private/krb5.conf /etc/ 7- Start and enable Samba Active Directory Domain Controller daemons: systemctl start samba-ad-dc.service systemctl status samba-ad-dc.service (You may get some error logs, like (Cannot contact any KDC for requested realm), which is okay. systemctl enable samba-ad-dc.service 8- Use netstat command in order to verify the list of all services required by an Active Directory to run properly. netstat –tulpn| egrep 'smbd|samba' 9- At this moment Samba should be fully operational at your premises. The highest domain level Samba is emulating should be Windows AD DC 2008 R2. It can be verified with the help of samba-tool utility. samba-tool domain level show 10- In order for DNS resolution to work locally, you need to open end edit network interface settings and point the DNS resolution by modifying dns-nameservers statement to the IP Address of your Domain Controller (use for local DNS resolution) and dns-search statement to point to your realm. When finished, reboot your server and take a look at your resolver file to make sure it points back to the right DNS name servers. 11- Test the DNS resolver by issuing queries and pings against some AD DC crucial records, as in the below excerpt. Replace the domain name accordingly. ping -c3 deskbit.local # Domain Name ping -c3 samba.deskbit.local # FQDN ping -c3 samba # Host

+ Date and Time (May 3, 2017, 12:12 p.m.)

Display Current Date and Time: $ date ---------------------------------------------------- Display The Hardware Clock (RTC): # hwclock -r OR show it in Coordinated Universal time (UTC): # hwclock --show --utc ---------------------------------------------------- Set Date Command Example: date -s "2 OCT 2006 18:00:00" OR date --set="2 OCT 2006 18:00:00" ---------------------------------------------------- Set Time Examples: date +%T -s "10:13:13" Use %p locale’s equivalent of either AM or PM, enter: # date +%T%p -s "6:10:30AM" # date +%T%p -s "12:10:30PM" ---------------------------------------------------- How do I set the Hardware Clock to the current System Time? Use the following syntax: # hwclock --systohc OR # hwclock -w ---------------------------------------------------- A note about systemd based Linux system With systemd based system you need to use the timedatectl command to set or view the current date and time. Most modern distro such as RHEL/CentOS v.7.x+, Fedora Linux, Debian, Ubuntu, Arch Linux and other systemd based system need to the timedatectl utility. Please note that the above command should work on modern system too. ---------------------------------------------------- timedatectl: Display the current date and time: $ timedatectl ---------------------------------------------------- Change the current date using the timedatectl command: # timedatectl set-time YYYY-MM-DD OR $ sudo timedatectl set-time YYYY-MM-DD For example set the current date to 2015-12-01 (1st, Dec, 2015): # timedatectl set-time '2015-12-01' # timedatectl ---------------------------------------------------- To change both the date and time, use the following syntax: # timedatectl set-time '2015-11-23 08:10:40' # date ---------------------------------------------------- To set the current time only: The syntax is: # timedatectl set-time HH:MM:SS # timedatectl set-time '10:42:43' # date ---------------------------------------------------- Set the time zone using timedatectl command: To see the list of all available time zones, enter: $ timedatectl list-timezones $ timedatectl list-timezones | more $ timedatectl list-timezones | grep -i asia $ timedatectl list-timezones | grep America/New To set the time zone to ‘Asia/Kolkata’, enter: # timedatectl set-timezone 'Asia/Kolkata' Verify it: # timedatectl ---------------------------------------------------- How to synchronizing the system clock with a remote server using NTP? # timedatectl set-ntp yes Verify it: $ timedatectl ---------------------------------------------------- For changing the timezone: dpkg-reconfigure tzdata ----------------------------------------------------

+ Extract ISO files (April 26, 2017, 10:58 a.m.)

sudo mount -o loop an_iso_file.iso /home/mohsen/Temp/foo/

+ reprepro (March 4, 2017, 10:16 a.m.) ------------------------------------------------------------------------- 1-Install GnuPG and generate a GPG key for Signing Packages: apt-get install gnupg dpkg-sig rng-tools ------------------------------------------------------------------------- 2-Open /etc/default/rng-tools: vim /etc/default/rng-tools and make sure you have the following line in it: [...] HRNGDEVICE=/dev/urandom [...] Then start rng-tools: /etc/init.d/rng-tools start ------------------------------------------------------------------------- 3-Generate your key: gpg --gen-key ------------------------------------------------------------------------- 4-Install and configure reprepro: apt-get install reprepro Let's use the directory /var/www/repo as the root directory for our repository. Create the directory /var/www/repo/conf: mkdir -p /var/www/repo/conf ------------------------------------------------------------------------- 5-Let's find out about the key we have created in step 3: gpg --list-keys Our public key is D753ED90. We have to use this from now on. ------------------------------------------------------------------------- 6-Create the file /var/www/repo/conf/distributions as follows: vim /var/www/repo/conf/distributions ------------------------------------------------------------------------- 7-The address of our apt repository will be, so we use this in the Origin and Label lines. In the SignWith line, we add our public key (D753ED90). Drop out the "2048R/" part: Origin: reprepro.deskbit.local Label: reprepro.deskbit.local Codename: stable Architectures: amd64 Components: main Description: Deskbit Proprietary Softwares SignWith: D753ED90 ------------------------------------------------------------------------- 8-Create the (empty) file /var/www/repo/conf/override.stable: touch /var/www/repo/conf/override.stable ------------------------------------------------------------------------- 9-Then create the file /var/www/repo/conf/options with this content: verbose ask-passphrase basedir /var/www/repo ------------------------------------------------------------------------- 10-To sign our deb packages with our public key, we need the package dpkg-sig: dpkg-sig -k D753ED90 --sign builder /usr/src/my-packages/*.deb ------------------------------------------------------------------------- 11-Now we import the deb packages into our apt repository: cd /var/www/repo reprepro includedeb stable /usr/src/my-packages/*.deb ------------------------------------------------------------------------- 12-Configuring nginx: We need a webserver to serve our apt repository. In this example, I'm using an nginx webserver. server { listen 80; server_name; access_log /var/log/nginx/packages-error.log; error_log /var/log/nginx/packages-error.log; location / { root /var/packages; index index.html; autoindex on; } location ~ /(.*)/conf { deny all; } location ~ /(.*)/db { deny all; } } *************************************************************************** OR for Apache: <VirtualHost *:80> ServerName reprepro.deskbit.local DocumentRoot /var/www/repo ServerName reprepro.deskbit.local ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined </VirtualHost> ------------------------------------------------------------------------- 13-Let's create a GPG key for the repository: gpg --armor --output /var/www/repo/ --export C7C1365D ------------------------------------------------------------------------- 14-To use the repository, place the following line in your /etc/apt/sources.list: vim /etc/apt/sources.list [...] deb stable main [...] ------------------------------------------------------------------------- 15-If you want this repository to always have precedence over other repositories, you should have this line right at the beginning of your /etc/apt/sources.list and add the following entry to /etc/apt/preferences: vim /etc/apt/preferences: Package: * Pin: origin Pin-Priority: 1001 ------------------------------------------------------------------------- 16-Before we can use the repository, we must import its key: wget -O - -q | apt-key add - apt-get update -------------------------------------------------------------------------

+ Packages to Install (Feb. 24, 2017, 8:45 a.m.)

pavucontrol proxychains android-tools-adb android-tools-fastboot gimp-plugin-registry gimp gir1.2-keybinder-3.0 quodlibet python3-dev python-dev libjpeg-dev libfreetype6 libfreetype6-dev zlib1g-dev zip python-setuptools vim postgresql-server-dev-all postgresql libpq-dev curl geany tmux git gdebi-core gdebi smplayer yakuake vlc gparted krita transmission-gtk htop graphicsmagick-imagemagick-compat network-manager-l2tp kaffeine pptp-linux network-manager-pptp simplescreenrecorder unrar geany-plugin-addons ------------------------------------------------------------------ pip3 install pipenv ------------------------------------------------------------------ Xtreme Download Manager: wget -O xdman.deb ------------------------------------------------------------------ Yakuake Add-on for Appearance: Cobalt2 Klorax. Retrofuturism Opaque ------------------------------------------------------------------

+ Faster grep (Jan. 7, 2017, 3:29 p.m.)

1- Install `parallel` sudo apt-get install parallel 2- Begin search: find . -type f | parallel -k -j150% -n 1000 -m grep -H -n "keyring doesn\'t exist" {}

+ Write ISO file to DVD in terminal (Sept. 3, 2016, 7:43 p.m.)

Using this command, check where the DVD Writer is mounted: (/dev/sr0) inxi -d And using this command, start writing on the DVD: wodim -eject -tao speed=8 dev=/dev/sr0 -v -data Downloads/linuxmint-18-kde-64bit-beta.iso

+ See Linux Version (Aug. 15, 2016, 1:56 p.m.)

cat /etc/os-release cat /etc/*release uname -a lsb_release -a

+ PyCharm / IntelliJ IDEA allows only two spaces (July 26, 2016, 11:07 a.m.)

In settings search for `EditorConfig` and disable the plugin.

+ Enable/Disalbe Bluetooth (July 26, 2016, 9:12 a.m.)

sudo rfkill block bluetooth sudo update-rc.d bluetooth disable service bluetooth status -------------------------------------------------------------------- sudo rfkill unblock bluetooth sudo update-rc.d bluetooth enable service bluetooth status --------------------------------------------------------------------

+ Error: Fixing recursive fault but reboot is needed! (July 17, 2016, 8:19 a.m.)

sudo nano /etc/default/grub Change: GRUB_CMDLINE_LINUX_DEFAULT GRUB_CMDLINE_LINUX To: GRUB_CMDLINE_LINUX_DEFAULT="quiet splash" GRUB_CMDLINE_LINUX="acpi=off" sudo update-grub2

+ No partitions found while installing Linux (July 15, 2016, 7:58 p.m.)

1- Boot up linux with Live CD (the installation disk) 2- sudo su 3- sudo apt-get install gdisk 4- sudo gdisk /dev/sda 5- Select (1) for MBR 6- Type x for expert stuff 7- Type z to zap the GPT data 8- Type y to proceed destroying GPT data 9- Type n in order to not lose MBR data Now restart the installation procedure.

+ Remove invalid characters from filenames (May 29, 2016, 6:48 a.m.)

find . -exec rename 's/[^\x00-\x7F]//g' "{}" \;

+ PyCharm Regex (May 23, 2016, 12:37 a.m.) {8}"name_ru": ".+?",\n ------------------------------------------------------------------- Search for any occurrences starting with a double quote: .?" -------------------------------------------------------------------

+ SASL authentication for IRC network using freenode (April 14, 2016, 6:06 p.m.) port: 6697 Make sure to use "Secure Connectsion (SSL)"

+ Batch rename files (March 11, 2016, 9:23 a.m.)

for file in *.html do mv "$file" "${file%.html}.txt" done --------------------------------------------------------------- for file in * do mv "$file" "$file.mp3" done --------------------------------------------------------------- Remove the word "crop_" in all files: for file in *; do mv "$file" "${file/crop_/}"; done ---------------------------------------------------------------

+ Genymotion (April 10, 2016, 5:52 p.m.)

1-apt-get install libdouble-conversion1 2-Download `Ubuntu 14.10 and older, Debian 8` genymotion version from the following link: The downloaded file name should be `genymotion-2.8.0-linux_x64.bin`. 3-sudo bash ./genymotion-2.8.0-linux_x64.bin 4-For running it, use this command: /opt/genymobile/genymotion/genymotion 5-You should already have the genymotion VirtualBox (ovd) files. If so, you need to change the path of VirtualBox Virtual devices in settings, to the location of your files. Settings --> Virtualbox (tab) --> Browse Hint: After this step I still could not see the list of virtual devices in genymotion program. I imported the ovd files in virtualbox program, and they got displayed in genymotion too.

+ ADB (Nov. 2, 2015, 3:34 p.m.)

sudo apt-get install android-tools-adb android-tools-fastboot

+ Gimp Plugin (Nov. 2, 2015, 3:33 p.m.)

sudo apt-get install gimp-plugin-registry

+ Diff over SSH (Oct. 12, 2015, 10:10 a.m.)

diff /home/mohsen/Projects/Shetab/nespresso/nespresso/ <(ssh 'cat /home/shetab/websites/nespresso/nespresso/')

+ Trim/Cut video files (Sept. 14, 2015, 12:33 p.m.)

ffmpeg -i video.mp4 -ss 10 -t 10 -c copy cut2.mp4 The first 10 is the start time in seconds: 10 ==> 10 seconds from start 1:10 ==> One minute and 10 seconds 1:10:10 ==> One hour, one minute and ten seconds The second 10 is the duration.

+ Retrieve Video File Information (Sept. 14, 2015, 10:32 a.m.)

mplayer -vo null -ao null -frames 0 -identify test.mp4

+ Change Hostname (Aug. 6, 2015, 9:44 p.m.)

nano /etc/hostname /etc/init.d/ start nano /etc/hosts service hostname restart

+ Get public IP address and email it (July 25, 2015, 11:47 a.m.)

Getting public IP address in bash: wget -qO- OR curl ------------------------------------------------------------ Getting it and emailing it (copy this script and paste it in a file with `.sh` extension): #/bin/sh IPADDRESS=$(wget -qO- # IPADDRESS=$(curl if [[ "${IPADDRESS}" != $(cat ~/.current_ip) ]] then echo "Your new IP address is ${IPADDRESS}" | mail -s "IP address change" echo ${IPADDRESS} >|~/.current_ip fi ------------------------------------------------------------

+ Libreoffice - Add/Remove RTL and LTR buttons to formating toolbar to Libreoffice (July 8, 2015, 6:11 p.m.)

You have to enable Complex Text Layout (CTL) support: 1- Tools → Options → Language Settings → Languages 2- Enable `Complex Text Layout (CTL)` 3- Select Persian 4- Restart libreoffice.

+ Installing Irancell 3G-4G Modem Driver (July 8, 2015, 9:23 a.m.)

1- sudo apt-get install g++-multilib libusb-dev libusb-0.1-4:i386 2- Connect the modem and copy the `linuxdrivers.tar.gz` file to your computer, extract it and cd to the directory. 3- CD to directory `drivers` and using the `install_driver` file, install the driver: sudo ./install_driver 4- Create a shortcut from the file `` to make the connection procedure easier: ln -s /home/mohsen/Programs/linuxdrivers/drivers/ . 5- To establish a connection use the command: sudo ~/ -------------------------------------------------------------------------- And this is the output: Looking for default devices ... Found default devices (1) Accessing device 007 on bus 003 ... USB description data (for identification) ------------------------- Manufacturer: Longcheer Product: LH9207 Serial No.: ------------------------- Looking for active driver ... No driver found. Either detached before or never attached Setting up communication with interface 0 ... Trying to send the message to endpoint 0x01 ... OK, message successfully sent -> Run lsusb to note any changes. Bye. sleep 3 ifconfig ecm0 up dhclient ecm0 mohsen drivers #

+ Quodlibet Multimedia Keys (June 3, 2015, 7:42 p.m.)

apt-get install gir1.2-keybinder-3.0

+ Connecting to wifi network through command line (June 3, 2015, 4:43 p.m.)

1- sudo iwlist wlan0 scan 2- sudo iwconfig wlan0 essid "THE SSID" 3- iwconfig wlan0 key s:password 4- sudo dhclient wlan0

+ Root Password Recovery (May 27, 2015, 11:54 a.m.)

rw init=/bin/bash

+ Locale Settings (Feb. 5, 2016, 12:10 a.m.)

This first solution has been worked. So before checking the other solutions, try this one first! nano /etc/environment LC_ALL=en_US.UTF-8 LANG=en_US.UTF-8 Restart server and it should be fixed now! ------------------------------------------------------------------------ locale-gen en_US.UTF-8 export LANGUAGE=en_US.UTF-8 export LANG=en_US.UTF-8 export LC_ALL=en_US.UTF-8 locale-gen en_US.UTF-8 dpkg-reconfigure locales ------------------------------------------------------------------------ This is a common problem if you are connecting remotely, so the solution is to not forward your locale. Edit /etc/ssh/ssh_config and comment out SendEnv LANG LC_* line. ------------------------------------------------------------------------

+ Environment Variable (April 3, 2015, 7:16 p.m.) --------------------------------------------------------------------------------------------- Commonly Used Shell Variables: --------------------------------------------------------------------------------------------- Use `set` command to display current environment --------------------------------------------------------------------------------------------- The $PATH defines the search path for commands. It is a colon-separated list of directories in which the shell looks for commands. --------------------------------------------------------------------------------------------- You can display the value of a variable using printf or echo command: $ echo "$HOME" --------------------------------------------------------------------------------------------- You can modify each environmental or system variable using the export command. Set the PATH environment variable to include the directory where you installed the bin directory with perl and shell scripts: export PATH=${PATH}:/home/vivek/bin OR export PATH=${PATH}:${HOME}/bin -------------------------------------------------------------------------------------------- You can set multiple paths as follows: export ANT_HOME=/path/to/ant/dir export PATH=${PATH}:${ANT_HOME}/bin:${JAVA_HOME}/bin --------------------------------------------------------------------------------------------- How Do I Make All Settings permanent? The ~/.bash_profile ($HOME/.bash_profile) or ~/.prfile file is executed when you login using console or remotely using ssh. Type the following command to edit ~/.bash_profile file, enter: $ vi ~/.bash_proflle Append the $PATH settings, enter: export PATH=${PATH}:${HOME}/bin Save and close the file. ---------------------------------------------------------------------------------------------------------

+ Ubuntu Sources List Generator (March 18, 2015, 2:22 p.m.)

+ Delete special files recursively (March 7, 2015, 1:06 p.m.)

find . -name "*.bak" -type f -delete find . -name "*.bak" -type f

+ How to stop services / programs from starting automatically (March 3, 2015, 9:57 a.m.)

update-rc.d -f apache2 remove

+ Truetype Fonts (Arial Font) (Feb. 22, 2015, 11:40 a.m.) --------------------------------------------------------------------------------------------- apt-get install ttf-liberation

+ Add Resolutions (Feb. 15, 2015, 9:49 a.m.)

1. Install arandr apt install arandr 2. Run "arandr" from the applications menu. 3. Create a resolution by doing the following: In this example, the resolution I want is 1920x1080 cvt 1920 1080 This will create a modeline like this: Modeline "1920x1080_60.00" 173.00 1920 2048 2248 2576 1080 1083 1088 1120 -hsync +vsync Create the new mode: xrandr --newmode "1920x1080_60.00" 173.00 1920 2048 2248 2576 1080 1083 1088 1120 -hsync +vsync 4. Add the mode (resolution) to the desired monitor: (Get the list of active outputs from the "output" menu in Arandr application) xrandr --addmode VGA-1 "1920x1080_60.00" 5- For switching to the newly created resolution: xrandr -s 1920x1080 OR xrandr --output VGA-1 --mode "1920x1080" OR Run "arandr" and position your monitors correctly from the "Outputs" -> "Resolutions" menu. 6. Choose 'layout' then 'Save As' to save the script 7. I found the best place to load the script (under Xubuntu) is the settings manager: xfce4-settings-manager OR Menu -> Settings -> Settings Manager -> Session and Startup -> Application Autostart You might need to update the script and add the 3 lines, instead of the single one that it has: xrandr --newmode "2560x1440_60.00" 312.25 2560 2752 3024 3488 1440 1443 1448 1493 -hsync +vsync xrandr --addmode Virtual-1 "2560x1440_60.00" xrandr --output Virtual-1 --mode 2560x1440_60.00 --pos 0x0 --rotate normal

+ Dump traffic on a network (Feb. 7, 2015, 10:03 a.m.)

tcpdump -nti any port 4301 To connect to it: telnet 4301

+ Show open ports and listening services (Feb. 7, 2015, 9:03 a.m.)

netstat -an | egrep 'Proto|LISTEN' netstat -lnptu -------------------------------------------------------------- netstat -tulpn | grep 389 -------------------------------------------------------------------

+ Make Bootable USB stick (Jan. 8, 2015, 6:20 p.m.)

1- Download Ventoy GUI and CLI tool from the following link: (Look for Linux in the Assets section) 2- Extract the tar gz file. Go inside the extracted folder and run sudo ./ 3- Ventoy runs inside a browser. It will show you the URL when you run it. Copy this URL and paste it into a browser. 4- When you hit the install button, it creates two partitions on the USB disk. - VTOYEFI: A small partition for the UEFI files. - Ventoy: A big, empty partition in ExFAT format where you’ll copy the ISO image. 5- Yes. That’s what you need to do. Copy the ISO image of Windows 10 into the bigger ExFAT partition on the USB disk. Once the copying finishes, DO NOT RUSH to plug out the USB just yet. Click on the unmount option from the file manager. Chances are that some files are still being written and it may show an error message.

+ Change locale/timezone and set the clock (Sept. 20, 2015, 12:27 p.m.)

1- ln -sf /usr/share/zoneinfo/Asia/Tehran /etc/localtime 2- apt install ntp 3- ntpd 4- hwclock -w ------------------------------------------------------------------- Linux Set Date Command Example # date -s "2 OCT 2006 18:00:00" OR # date --set="2 OCT 2006 18:00:00" OR # date +%Y%m%d -s "20081128" OR # date +%T -s "10:13:13" Where, 10: Hour (hh) 13: Minute (mm) 13: Second (ss) Use %p locale's equivalent of either AM or PM, enter: # date +%T%p -s "6:10:30AM" # date +%T%p -s "12:10:30PM" ------------------------------------------------------------------- yum install ntp ln -sf /usr/share/zoneinfo/Asia/Tehran /etc/localtime /etc/init.d/ntpd stop ntpdate -------------------------------------------------------------------

+ Split and Join/Merging Files (Nov. 28, 2014, 10:28 a.m.)

split --bytes=1M NimkatOnline-1.0.0.apk NimkatOnline -l ==> lines b ==> bytes M ==> Megabyte G ==> Gigabytes split --bytes=1M images/myimage.jpg new split -b 22 newfile.txt new Split the file newfile.txt into three separate files called newaa, newab and newac..., with each file containing 22 bytes of data. split -l 300 file.txt new Split the file newfile.txt into files beginning with the name new, each containing 300 lines of text. ------------------------------------------------------------- For merging or joining files: cat new* > newimage.jpg -------------------------------------------------------------

+ Locate (Nov. 13, 2014, 8:33 p.m.)

Match the exact filename: locate -b '\filename' ------------------------------------------------------------- Don’t output all the results, but only the number of matching entries. locate -c test -------------------------------------------------------------

+ SSH login without password (Nov. 13, 2014, 5:59 p.m.)

1- ssh-keygen -t rsa (No need to set a password) 2- ssh-copy-id Now you can log in without a password

+ APT - The location where apt-get caches/stores .deb files (Oct. 18, 2014, 5:46 a.m.)


+ Recover Files (Sept. 14, 2014, 5:54 p.m.)

Using this program you can undelete/recover deleted files: testdisk After selecting the desired Hard Disk, press capital (p) the `P` key to show all the deleted files.

+ Setting Proxy Variable (Aug. 22, 2014, 11:14 a.m.)

export http_proxy="localhost:9000" export https_proxy="localhost:9000" export ftp_proxy="localhost:9000" And for removing environment variables: unset http_proxy unset https_proxy unset ftp_proxy

+ Getting folder size (Aug. 22, 2014, 11:08 a.m.)

du -sh /path/to/directory

+ Join *.001, *.002, .... files (Aug. 22, 2014, 11:03 a.m.)

cat filename.avi.* > filename.avi

+ ISO files (Aug. 22, 2014, 11:03 a.m.)

Convert .DAA Files To .ISO Download and install power PowerISO using the following link: Scroll to the bottom of the page, in `Other downloads` section to get the linux version. 1- wget 2- tar -zxvf poweriso-1.3.tar.gz 3- You can copy the extracted file “poweriso” to /usr/bin to help all users of a computer to use it. Now if you want to convert for example a .daa file to .iso use this command: poweriso convert /path/to/source.daa -o /path/to/target.iso -ot iso There are more useful commands of poweriso: Task: list all files and directories in home direcory of /media/file.iso poweriso list /media/file.iso / poweriso list /media/file.iso / -r ******* Fore more commands please type poweriso -? -------------------------------------------------------------------------------------- Convert DMG to ISO 1- Install the tool sudo apt-get install dmg2img 2- The following command will convert the .dmg to .img file in ISO format: dmg2img <file_name>.dmg 3- And finally, rename the extension: mv <file_name>.img <file_name>.iso -------------------------------------------------------------------------------------- Create ISO file from a directory: mkisofs -allow-limited-size -o abcd.iso abcd --------------------------------------------------------------------------------------

+ Nautilus Bookmarks (Aug. 22, 2014, 10:56 a.m.)

Nautilus bookmarks configuration file location: ~/.config/gtk-3.0/bookmarks For seeing which version of nautilus you have: nautilus --version

+ Convert mp3 to ogg (Aug. 22, 2014, 11:02 a.m.)

1- apt-get install mpg321 vorbis-tools 2- mpg321 input.mp3 -w raw && oggenc raw -o output.ogg

+ Convert rmp to deb (Aug. 22, 2014, 10:56 a.m.)

1- apt-get install alien 2- alien -d package-name.rpm

+ Tmux (Aug. 22, 2014, 11:01 a.m.)

Creating sessions: tmux new -s mohsen_session -------------------------------------------------------------------------- Attaching and detaching: tmux a tmux attach tmux attach -t mohsen_session -------------------------------------------------------------------------- Listing sessions: tmux ls -------------------------------------------------------------------------- Killing tmux entirely: :kill-server -------------------------------------------------------------------------- Prompt not following normal bash colors: For fixing the problem, create a file `~/.tmux.conf` if it does not exist, and add the following to it: set -g default-terminal "screen-256color" set -g history-limit 100000 -------------------------------------------------------------------------- Tmux Plugin Manager: git clone ~/.tmux/plugins/tpm Put this at the bottom of ~/.tmux.conf: # List of plugins set -g @plugin 'tmux-plugins/tpm' set -g @plugin 'tmux-plugins/tmux-sensible' # Initialize TMUX plugin manager (keep this line at the very bottom of tmux.conf) run '~/.tmux/plugins/tpm/tpm' -------------------------------------------------------------------------- Installing plugins: 1-Add new plugin to ~/.tmux.conf with set -g @plugin '...' 2-Press prefix + I (capital I, as in Install) to fetch the plugin. -------------------------------------------------------------------------- Uninstalling plugins: 1-Remove (or comment out) plugin from the list. 2-Press prefix + alt + u (lowercase u as in uninstall) to remove the plugin. -------------------------------------------------------------------------- Tmux-continuum plugin: set -g @plugin 'tmux-plugins/tmux-resurrect' set -g @plugin 'tmux-plugins/tmux-continuum' Automatic restore: Last saved environment is automatically restored when tmux is started. Put this in tmux.conf to enable: set -g @continuum-restore 'on' set -g @resurrect-capture-pane-contents 'on' -------------------------------------------------------------------------- CPU/RAM/battery stats chart bar: install the plugin using CPAN: sudo cpan -i App::rainbarf If it's the first time you're using CPAN you might be asked to let some plugins get installed automatically... You choose (yes) and then choose(sudo) to let the plugin installed. After installation, create a config file ~/.rainbarf.conf with this content: width=20 # widget width bolt # fancy charging character remaining # display remaining battery rgb # 256-colored palette -------------------------------------------------------------------------- Whole config file: set -g default-terminal "screen-256color" set-option -g status-utf8 on set -g @plugin 'tmux-plugins/tpm' set -g @plugin 'tmux-plugins/tmux-sensible' set -g @plugin 'tmux-plugins/tmux-resurrect' set -g @plugin 'tmux-plugins/tmux-continuum' set -g @plugin 'tmux-plugins/tmux-logging' set -g @continuum-restore 'on' set -g @resurrect-capture-pane-contents 'on' set -g history-limit 500000 set -g status-right '#(rainbarf)' set -g default-command bash run '~/.tmux/plugins/tpm/tpm' -------------------------------------------------------------------------- PRESS CTRL+B and CTRL+I to install plugins after editing the .tmux.conf file. -------------------------------------------------------------------------- CTRL + B and SHIFT + P to start (and end) logging in current pane. CTRL + B and ALT + P to start (and end) to capture screen. Save complete history: CTRL + B and ALT + SHIFT + P Clear pane history: CTRL + B and ALT + C -------------------------------------------------------------------------- Swap Window: swap-window -s 3 -t 1 -------------------------------------------------------------------------- Copy paste in Tmux: 1- Enter copy mode using Control+b [ 2- Navigate to beginning of text, you want to select and hit Control+Space. 3- Move around using arrow keys to select region. 4- When you reach end of region simply hit Alt+w to copy the region. 5- Now Control+b ] will paste the selection. --------------------------------------------------------------------------

+ Undeleteing (Aug. 22, 2014, 11 a.m.)

1- Install extundelete: apt-get install extundelete 2- Either "unmount" or "remount" the partition as read-only: sudo mount -t vfat -O remount,ro /dev/sdb /mnt To remount it back to read-write: (This task is not part of this tutorial. It's just for keeping a note.) sudo mount -t vfat -O remount,rw /dev/sdb /mnt 3- For restoring the files from the whole partition: extundelete /dev/sdb1 –restore-all And for restoring important files quickly, you may use the --restore-file, --restore-files, or --restore-directory options.

+ Error - ia32-libs : Depends: ia32-libs-i386 but it is not installable (Aug. 22, 2014, 10:59 a.m.)

The ia32-libs-i386 package is only installable from the i386 repository, which becomes available with the following commands: dpkg --add-architecture i386 apt-get update

+ Driver - Samsung Printer (July 20, 2015, 9:53 p.m.) Installing My Samsung Printer Driver (SCX-4521F): 1-Add the following repository to /etc/apt/sources.list: deb debian extra 2-Install the GPG key: sudo apt-get install suldr-keyring apt-get update 3-Install these packages: apt-get install samsungmfp-driver-4.00.39 suld-configurator-2-qt4

+ Grub rescue (Aug. 22, 2014, 10:32 a.m.)

I haven't tried it yet, so keep in mind to correct the problems: mount /dev/masax /mnt groub-install --root-directory=/mnt/ /dev/sda OR Another day I just used these commands, some would give me errors, but some would work...but in my surprise it worked: set prefix=(hd0,1)/boot/grub insmod (hd0,1)/boot/grub/linux.mod insmod part_msdos insmod ext2 set root=(hd0,1) reboot using CTRL+ALT+DELETE

+ Commands - iftop (Aug. 22, 2014, 10:53 a.m.)

iftop: InterFace Table of Processes Install iftop for viewing what applications are using/eating up Internet. iftop -i eth1 # The logs from xchat help: in iftop hit `p` to toggle port display now you know which port on your machine is connecting out to that domain now use netstat -nlp to list all pids on which ports are connecting out you should now know which pid is hitting that domain... provided all traffic originates on your local box also consider using lsof for this sort of mining

+ unrar (Aug. 22, 2014, 10:33 a.m.)

Recurse subdirectories: unrar x -r <parent directory --------------------------------------------------------------------- unrar e file.rar unrar l file.rar --------------------------------------------------------------------- Unrar all files: for file in *.part01.rar; do unrar x ${file}; done; ---------------------------------------------------------------------

+ Swap file (Aug. 22, 2014, 10:32 a.m.)

Create a swap file: 1- dd if=/dev/zero of=/swapfile1 bs=1024 count=524288 Where, if=/dev/zero : Read from /dev/zero file. /dev/zero is a special file in that provides as many null characters to build storage file called /swapfile1. of=/swapfile1 : Read from /dev/zero write stoage file to /swapfile1. bs=1024 : Read and write 1024 BYTES bytes at a time. count=524288 : Copy only 523288 BLOCKS input blocks. 2- mkswap /swapfile1 3- chown root:root /swapfile1 chmod 0600 /swapfile1 4- swapon /swapfile1 5- nano /etc/fstab Append the following line: /swapfile1 swap swap defaults 0 0 6- To test/see the free space: free -m

+ Aliases (Aug. 22, 2014, 10:30 a.m.)

Defining alias: 1- Open the file ~/.bashrc and write an alias like this: alias myvps='ssh -p 54321' 2- Enter this command to make the changes affect: source .bashrc Keep in mind that every time a change is done to .bashrc file, you have to reload it with: source .bashrc

+ Backlight (Screen Brightness) (Aug. 22, 2014, 10:02 a.m.)

For solving the back light brightness problem, got to /etc/default/grub and edit the line: GRUB_CMDLINE_LINUX_DEFAULT to: GRUB_CMDLINE_LINUX_DEFAULT="quiet acpi_osi=Linux acpi_backlight=vendor splash" And then: update-grub2 ---------------------------------------------------------------------------- Check if graphics card is intel: ls /sys/class/backlight You should see something like: ideapad intel_backlight ---------------------------------------------------------------------------- Fix backlight: Create this file: /usr/share/X11/xorg.conf.d/20-intel.conf Section "Device" Driver "intel" Option "Backlight" "intel_backlight" Identifier "card0" EndSection Logout and Login. Done. ----------------------------------------------------------------------------

+ IRC (Aug. 22, 2014, 9:58 a.m.)

1- Join the Freenode network. Open your favorite IRC client and type: /server 2- Choose a username or nickname. The username should consist only of the letters A-Z, the numbers 0-9, and certain symbols such as "_" and "-". It may have a maximum of 16 characters. 3- Change your username to the one you have chosen. Suppose you chose the nickname "awesomenickname". Type the following in the window titled Freenode: /nick awesomenickname 4- Register your nick or username. Type the following command and replace "your_password" with a password that will be easy to remember, and replace "your_email_address" with your email address. /msg nickserv register your_password your_email_address 5- Verify your registration. After you register, you will not be able to identify to NickServ until you have verified your registration. To do this, check your email for an account verification code. 6- Group an alternate nickname with your main one. If you would like to register an alternate nickname, first switch to the alternate nickname that you want while you are identified as the main one, then group your nicks together with this command: /msg nickserv group 7- Identify with Nickserv. Each time you connect, you should sign in, or "identify" yourself, using the following command: /msg nickserv identify your_password ------------------------------------------------------------------------------------------ You can send private messages anytime after step 4. The advantage of the other steps is to make your registration much more secure. To send a private message, you simply do the following, replacing Nick with the nickname or username of the person you wish to contact privately and message with the message you want to start with: /msg Nick message Take care to follow this process in the Freenode window, not directly in a channel. If you type all the commands correctly, nothing should be visible to others, but it's very easy to type something else by mistake, and in so doing, you could expose your password. Choose a nick between 5 and 8 characters long. This will make it easier to identify and avoid confusion. Choose your nick wisely. Remember that users will identify this name with your person. Usernames will automatically expire after 60 days of disuse. This is counted from the last time it was identified with NickServ. If the nickname you want is not in use and you want it, you can contact somebody with Freenode staff to unassign it for you. If you will not be able to use IRC for 60 days you can extend the time using the vacation command (/msg nickserv vacation). Vacation will be disabled automatically next time you identify to NickServ. To check when a nick was last identified with NickServ, use /msg NickServ info Nick The Freenode staff have an option enabled to receive private messages from unregistered users so if you wish to request that a nick be freed, you do not have to register another. To contact a member of the staff, use the command /stats p or /quote stats p if the first doesn't work. Send them a private message using /query nick. In case there is no available staff member in /stats p, use /who freenode/staff/* or join the channel #freenode using /join #freenode. Avoid using usernames that are brand names or famous people, to avoid conflicts. If you don't want your IP to be seen to the public, contact FreeNode staff and they can give you a generic "unaffiliated" user cloak, if you are not a member of a project. If you want to hide your email address, use /msg nickserv set hidemail on. If you need to change your password, type /ns set password new_password. You will need to be logged in. ------------------------------------------------------------------------------------------ # select nick name /nick yournickname # better don't show your email address: /ns set hide email on # register (only one time needed) - PW is in clear text!! /msg NickServ register [password] [email] # identify yourself to the IRC server (always needed) (xxxx == pw) /msg NickServ IDENTIFY xxxx # Join a channel /join #grass ------------------------------------------------------------------------------------------ Registering a channel: 1- To check whether a channel has already been registered, use the command: /msg ChanServ info #Mohsen or ##Mohsen 2- /join #Mohsen 3- /msg ChanServ register #Mohsen ------------------------------------------------------------------------------------------ For gaining OP: /MSG chanserv op #my_channel Mohsen_Hassani ------------------------------------------------------------------------------------------

+ ZIP (Aug. 22, 2014, 9:55 a.m.)

To zip just one file file.txt: zip file.txt --------------------------------------------------------------------------- To zip an entire directory: zip -r directory --------------------------------------------------------------------------- Create a password-protected zip file named zip -r -e the_directory --------------------------------------------------------------------------- Unzip to a directory: unzip -d music --------------------------------------------------------------------------- For excluding a directory in ZIP: zip -r test -x "path/to/exclusion/directory/*" ---------------------------------------------------------------------------

+ Commands - ssh (Aug. 22, 2014, 9:52 a.m.)

SSH is some kind of an abbreviation of Secure SHell. It is a protocol that allows secure connections between computers. To move the ssh service to another port: ssh -p yourport yourusername@yourserver Running a command on the remote server: Sometimes, especially in scripts, you'll want to connect to the remote server, run a single command and then exit again. The ssh command has a nice feature for this. You can just specify the command after the options, username and hostname. Have a look at this: ssh yourusername@yourserver updatedb This will make the server update its searching database. Of course, this is a very simple command without arguments. What if you'd want to tell someone about the latest news you read on the web? You might think that the following will give him/her that message: ssh yourusername@yourserver wall "Hey, I just found out something great! Have a look at!" However, bash will give an error if you run this command: bash: !": event not found What happened? Bash (the program behind your shell) tried to interpret the command you wanted to give ssh. This fails because there are exclamation marks in the command, which bash will interpret as special characters that should initiate a bash function. But we don't want this, we just want bash to give the command to ssh! Well, there's a very simple way to tell bash not to worry about the contents of the command but just pass it on to ssh already: wrapping it in single quotes. Have a look at this: ssh yourusername@yourserver 'wall "Hey, I just found out something great! Have a look at!"' The single quotes prevent bash from trying to interpret the command, so ssh receives it unmodified and can send it to the server as it should. Don't forget that the single quotes should be around the whole command, not anywhere else. ------------------ sudo ssh-keygen -R hostname ------------------ Creating ssh key: ssh-keygen -t rsa ------------------ When the server is just installed, the first access is possible via: ssh-keygen -R <ip of server> ------------------ SSH Tunnel: 1-Create a user on the server: adduser <username> 2-Copy the user's ssh_key from his computer to the server: ssh-copy-id -i ~/.ssh/ <username>@<server_ip> 3-Run this command on user's computer: ssh -D <an optional port, like 9000> -fN <username>@<server_ip> 4-Change the Connection Settings of Mozilla, SOCKS Host: localhost 9000

+ GPG (Aug. 22, 2014, 9:51 a.m.)

1- apt install dirmngr 2- apt-key adv --keyserver --recv-keys DB141E2302FDF932

+ wget (Aug. 22, 2014, 9:48 a.m.)

ERROR: The certificate of `' is not trusted. ERROR: The certificate of `' hasn't got a known issuer. wget --no-check-certificate <url_link> ------------------------------------------------------------- Mirror an entire website wget -m ------------------------------------------------------------- Mirror entire website: wget --mirror --random-wait --convert-links --adjust-extension --page-requisites --no-host-directories -erobots=off --no-cache ------------------------------------------------------------- Print file to stdout like curl does: wget -O - ------------------------------------------------------------- Recursively download only files with the pdf extension up to two levels away: wget -r -l 2 -A "*.pdf" or Rejetct some specific files: wget -A "*.mp3" -R "*.mp4" ------------------------------------------------------------- Get your external ip address from and echo to STDOUT: wget -O - | tail ------------------------------------------------------------- Open tarball without downloading: wget -qO - "" | tar zxvf - ------------------------------------------------------------- The option -c or --continue will resume an interrupted download: wget -c ------------------------------------------------------------- Download a list of URLs from a file: wget -i urls.txt ------------------------------------------------------------- Save the file into a directory: wget -P path/to/directory ------------------------------------------------------------- Saves the HTML of a webpage to a particular file: wget -O bro.html ------------------------------------------------------------- Download the entire website: Short Version: wget --user-agent="Mozilla" -mkEp -np Explanation: wget --mirror --convert-links --adjust-extension --page-requisites --no-parent Explanation of the various flags: --mirror – Makes (among other things) the download recursive. --convert-links – convert all the links (also to stuff like CSS stylesheets) to a relative, so it will be suitable for offline viewing. --adjust-extension – Adds suitable extensions to filenames (html or css) depending on their content-type. --page-requisites – Download things like CSS style-sheets and images required to properly display the page offline. --no-parent – When recursing do not ascend to the parent directory. It is useful for restricting the download to only a portion of the site. -------------------------------------------------------------

+ Commands - lsof (Aug. 22, 2014, 9:42 a.m.)

lsof -i:<port> Example: lsof -i:80 Displays the process which uses the port 80. ----------------------------------------------------------

+ Commands - ps (Aug. 22, 2014, 9:36 a.m.)

ps Lists all processes ---------------------------------------------------------- ps -A Displays all processes ---------------------------------------------------------- kill + PID of process Terminates a process ----------------------------------------------------------

+ Changing the attributes of a file/directory (Aug. 22, 2014, 9:35 a.m.)

The attributes are read/write/execute for root/user/group with the values being: 4-2-1, 4-2-1, 4-2-1. -------------------------------------------------------------- To give everyone execute-only permission to a file: chmod 111 -------------------------------------------------------------- or all permissions, it'd be chmod 777 -------------------------------------------------------------- Root only r/w/x would be chmod 700 -------------------------------------------------------------- 4 = owner 2 = group 1 = other --------------------------------------------------------------

+ Commands - ls (Aug. 22, 2014, 9:34 a.m.)

ls -r Reverse order while sorting -------------------------------------------------------------- ls -F Shows executable files with '*' sign and link files with '@' -------------------------------------------------------------- ls -t Sort by time --------------------------------------------------------------

+ Shutting down (Aug. 22, 2014, 9:12 a.m.)

shutdown -r now shutdown -r 7:00

+ Directories (Aug. 22, 2014, 8:58 a.m.)

/bin - Essential user commands The /bin directory contains essential commands that every user will need. This includes your login shell and basic utilities like ls. The contents of this directory are usually fixed at the time you install Linux. Programs you install later will usually go elsewhere. --------------------------------------------------------------------------------- /usr/bin - Most user commands The /usr hierarchy contains the programs and related files meant for users. (The original Unix makers had a thing for abbreviation.) The /usr/bin directory contains the program binaries. If you just installed a software package and don't know where the binary went, this is the first place to look. A typical desktop system will have many programs here. --------------------------------------------------------------------------------- /usr/local/bin - "Local" commands When you compile software from source code, those install files are usually kept separate from those provided as part of your Linux distribution. That is what the /usr/local/ hierarchy is for. --------------------------------------------------------------------------------- /sbin - Essential System Admin Commands The /sbin directory contains programs needed by the system administrator, like fsck, which is used to check file systems for errors. Like /bin, /sbin is populated when you install your Linux system, and rarely changes. --------------------------------------------------------------------------------- /usr/sbin - Non-essential System Administration Programs (binaries) This is where you will find commands for optional system services and network servers. Desktop tools will not show up here, but if you just installed a new mail server, this is where to look for the binaries. --------------------------------------------------------------------------------- /usr/local/sbin - "Local" System Administration Commands When you compile servers or administration utilities from source code, this is where the binaries normally will go. --------------------------------------------------------------------------------- Libraries: Libraries are shared bits of code. On Windows these are called DLL files (Dynamic Loading Libraries). On Linux systems they are usually called SO (Shared Object) files. As to location, are you detecting a pattern yet? There are three directories where library files are placed: /lib, /usr/lib, and /usr/local/lib. --------------------------------------------------------------------------------- Documentation: Documentation is a minor exception to the pattern of file placement. Pages of the system manual (man pages) follow the same pattern as the programs they document: /man, /usr/man, and /usr/local/man. You should not access these files directly, however, but by using the man command. Many programs install addition documentation in the form of text files, HTML, or other things not man pages. This extra documentation is stored in directories under /usr/share/doc or /usr/local/share/doc. (On older systems you may find this under /usr/doc instead.) ---------------------------------------------------------------------------------

+ Tarballs (Tar Archive) (Aug. 22, 2014, 8:51 a.m.)

tar -xzvf filename.tar.gz x : eXtract j : deal with bzipped file f : read from a file (rather than a tape device) ------------------------------------------------------------- Creating a tar File: tar -cvf output.tar /dirname tar -cvf Projects.tar Projects --exclude=Projects/virtualenvs --exclude=".buildozer" --exclude=".git" tar -cvf output.tar /dirname1 /dirname2 filename1 filename2 tar -cvf output.tar /home/vivek/data /home/vivek/pictures /home/vivek/file.txt tar -cvf /tmp/output.tar /home/vivek/data /home/vivek/pictures /home/vivek/file.txt Where, -c : Create a tar ball. -v : Verbose output (show progress). -f : Output tar ball archive file name. -x : Extract all files from archive.tar. -t : Display the contents (file list) of an archive. ------------------------------------------------------------- Create a tar Archive File: tar -cf abcd.tar /home/mohsen/abcd Untar Single file from tar File: tar -xf abcd.tar x.png OR tar --extract --file=abcd.tar x.png Untar Multiple files: tar -xf abcd.tar "x.png" "y.png" "z.png" ------------------------------------------------------------- Create tar.gz Archive File (compressed gzip archive): tar -czf abcd.gz /home/mohsen/abcd Uncompress tar.gz Archive File: tar -xf abcd.tar.gz tar -xf abcd.tar.gz -C /home/mohsen/Temp/ List Content tar.gz Archive File: tar -tvf abcd.tar.gz Untar Single file from tar.gz File: tar -zxf abcd.tar.gz x.png tar --extract --file=abcd.tar.gz x.png Untar Multiple files: tar -zxf abcd.tar.gz "x.png" "y.png" "z.png" ------------------------------------------------------------- Create tar.bz2 Archive File: The bz2 feature compresses and creates archive files less than the size of the gzip. The bz2 compression takes more time to compress and decompress files as compared to gzip which takes less time. tar -cfj abcd.tar.bz2 /home/mohsen/abcd Uncompress tar.bz2 Archive File: tar -xf abcd.tar.bz2 List content tar.bz2 archive file: tar -tvf abcd.tar.bz2 Untar single file from tar.bz2 File: tar -jxf abcd.tar.bz2 home/mohsen/x.png tar --extract --file=abcd.tar.bz2 /home/mohsen/x.png Untar multiple files: tar -jxf abcd.tar.bz2 "x.png" "y.png" "z.png" ------------------------------------------------------------- Extract group of files using wildcard: tar -xf abcd.tar --wildcards '*.png' tar -zxf abcd.tar.gz --wildcards '*.png' tar -jxf abcd.tar.bz2 --wildcards '*.png' ------------------------------------------------------------- Add files or directories to tar archive file: Use the option r (append) tar -rf abcd.tar m.png tar -rf abcd.tar images The tar command doesn’t have an option to add files or directories to an existing compressed tar.gz and tar.bz2 archive file. If we do try will get the following error: tar: This does not look like a tar archive tar: Skipping to next header ------------------------------------------------------------- Create a tar archive using xz compression: tar -cJf abcd.tar.xz /path/to/archive/ Decompression: tar xf abcd.tar.xz ------------------------------------------------------------- Compress supporting source and destination directory: tar -cf /home/mohsen/Temp/abcd.tar -P /home/mohsen/Temp/abcd tar -cPf /home/mohsen/Temp/abcd.tar /home/mohsen/Temp/abcd ------------------------------------------------------------- Tar Usage and Options: c – create a archive file. x – extract a archive file. v – show the progress of archive file. f – filename of archive file. t – viewing content of archive file. j – filter archive through bzip2. z – filter archive through gzip. r – append or update files or directories to existing archive file. W – Verify a archive file. wildcards – Specify patterns in unix tar command. -P (--absolute-names) – don't strip leading '/'s from file names ------------------------------------------------------------- xz: tar -cJf my_folder.tar.xz my_folder ------------------------------------------------------------- tar zc --exclude node_modules -f tiptong.tar.gz tiptong ------------------------------------------------------------- Extract to a different directory: tar -xf -C /path/to/directory tar xf file.tar --directory /path/to/directory -------------------------------------------------------------

+ apt-get (Aug. 22, 2014, 8:51 a.m.)

apt-get upgrade Updating the software apt-get -s upgrade To simulate an update installation, i.e. to see which software will be updated.

+ Search for text in files (Aug. 9, 2015, 8:15 p.m.)

find . -name "*.txt" | xargs grep -i "text_pattern" ------------------------------------------------------------------------ find / -type f -exec grep -l "text-to-find-here" {} \; ------------------------------------------------------------------------ grep word_to_find file_name -n --c The --c is for coloring the words ------------------------------------------------------------------------ grep "<the word or text to be searched>" / -Rn --color -T Description: /: The location to be searched R: Search in recursive mode n: Display the number of the line in which the occurrence word or text is located color: Display the search result colored T: Separate the search result with a tab l: stands for "show the file name, not the result itself" ------------------------------------------------------------------------ grep -Rin "text-to-find-here" / OR grep --color -Rin "text-to-find-here" / (to make it colorful) OR egrep -w -R 'word1|word2' ~/projects/ (for two words) i stands for upper/lower case w stands for the whole word ---------------------------------------------------------------- Find specific files and search for specific words: find . -name '*.py' -exec grep -Rin 'resize' {} + Finds the word `resize` in python files. OR find -iname "*.py" | xargs grep -i django ---------------------------------------------------------------- Command "grep", only in certain file extensions: grep -Rnw 'YEAR' --include \*.py ----------------------------------------------------------------

+ dpkg (Aug. 22, 2014, 8:49 a.m.)

dpkg --get-selections To get list of all installed software dpkg-query -W To get list of installed software packages dpkg -l Description of installed software packages

+ sources.list (Aug. 22, 2014, 8:28 a.m.)

deb jessie/updates main deb-src jessie/updates main deb jessie-updates main deb-src jessie-updates main deb jessie main deb-src jessie main ---------------------------------------------------------------------------------------- deb stretch main deb-src stretch main deb stretch-updates main deb-src stretch-updates main deb stretch/updates main deb-src stretch/updates main ----------------------------------------------------------------------------------------

+ Irancell WiMAX modem (Aug. 17, 2015, 8:25 a.m.)

For installing the driver, install these packages first: apt-get install linux-headers-`uname -r` libssl-dev usb-modeswitch zip --------------------------------------------------------------------------------------------- The wimaxd would not get recognized by the terminal. So I copied it in the /bin directory. There was an error "error while loading shared libraries: cannot open shared object file" so I did the following: To fix the problem, I added the "" path to /etc/ and re-ran ldconfig. Another incident which is not related to WiMAX, is that, one day when I was installing and running Apache, there was an error similar to this error of WiMAX: "error while loading shared libraries: cannot open shared object file", so I searched for the file using "locate" command and copied it in the address "/usr/lib" and ran Apache, it was solved! --------------------------------------------------------------------------------------------- WiMAX linux-headers error: make: *** /lib/modules/3.13.0-37-generic/source: No such file or directory. Stop. 1-rm /lib/modules/3.13.0-37-generic/source 2-ln -s /usr/src/linux-headers-3.13.0-37 /lib/modules/3.13.0-37-generic/source -------------------------------------------------------------------------------------------- Usage: 1-su 2-wimaxd -D -c wimaxd.conf 3- (in another console) wimaxc -i 3.1-search 3.2-connect 4-(in another console) su 4.1-dhclient eth1 --------------------------------------------------------------------------------------------

+ Version, Distro, Release (Aug. 4, 2014, 3:08 a.m.)

uname -r ---------------------------------------------------------------------------- Find or identify which version of Debian Linux you are running: cat /etc/debian_version ---------------------------------------------------------------------------- What is my current linux distribution cat /etc/issue ---------------------------------------------------------------------------- How Do I Find Out My Kernel Version? uname -mrs ---------------------------------------------------------------------------- lsb_release Command: The lsb_release command displays certain LSB (Linux Standard Base) and distribution-specific information. lsb_release -a ----------------------------------------------------------------------------

+ Hardware & Driver information (Aug. 4, 2014, 3:07 a.m.)

lshw ---------------------------------------------------------------------------- See PCI devices along with their kernel modules (device drivers): lspci -k It first shows you all the PCI devices attached to your system and then tells you what kernel modules (device drivers), are being used by them. ---------------------------------------------------------------------------- Identify Computer Model: sudo grep "" /sys/class/dmi/id/[bpc]* ----------------------------------------------------------------------------

+ Sudoer (Aug. 4, 2014, 3:06 a.m.)

visudo Scroll to the bottom of the page and enter: mohsen ALL=(ALL) ALL