Experimental Environment: Ubuntu 18.04 Remote Server + WSL2 Local Machine
Functional Requirements#
Final Result#
Based on the realization of the above functions, additional features such as 【real-time stock data, last login time, total usage time this month】 were added, with certain fault tolerance 【Shell judgment, default value returned on API call failure】, and some experimental features, see the end of the article 【On This Day in History, Rejected Visitors, Command Statistics from Last Login, Display Image in Terminal】
- em.. today doesn't seem to be a good day, the stock market is down :)
——>Time Reversal Below<——
Implementation Process#
【First, take a look at the default message when connecting to the host】
- I don't want any of these messages, starting from scratch, to create a completely self-made [patchwork] message reminder
Remove Original Boot Information#
How to remove the above information?
- Guided by an expert [Captain of the Ship], "Go to /etc/update-motd.d to take a look," vim update-motd.d shows as follows:
- Originally thought it was a file... opening each file corresponds to the above login information
- Here, motd means message of the day
- It can be updated every time you log in; or it can be pre-stored and unchanged
- Refer to man 5 update-motd, here is referenced What is MOTD?-cnblogs
- It mentions that the output of MOTD is managed by a login module under a service called pam, sudo vim /etc/pam.d/login, commenting out the functions related to motd, but it does not take effect
- It turns out that /etc/pam.d/login is used to control local logins, while I use SSH to log in, there is another configuration file /etc/pam.d/sshd
- Refer to Disable everything in update-motd.d dir in ubuntu server-StackExchange
- I want to disable the login prompt message after connecting via SSH, so I enter sudo vim /etc/pam.d/sshd
- Comment out the functions related to motd
- I want to disable the displayed messages in update-motd.d, which are dynamic information, so just comment out line 33
- The source of static messages /etc/motd does not exist on the host, so it can be ignored
【Reconnect to the host, much cleaner】
- But there is still a Last login information
- It is controlled by sshd, find the sshd configuration file
- sudo vim /etc/ssh/sshd_config, set PrintLastLog to no
- Restart the sshd service to make it effective, sudo service sshd restart [Feels Familiar]
【At this point, back to the pre-liberation state】
Preliminary Preparation#
Find the Boot Running Files#
【Using zsh boot configuration file】
Shell: zsh
- Search FILES through man zsh to view the zsh boot configuration files, there are many
- Based on context, use .zlogin configuration
- Create .zlogin in the home directory, vim ~/.zlogin
Recent Login Count [This Month]#
【This Month Login: 40 times】
【Obtain through last】
- Current user
- By extracting the first element of who am i: who am i | cut -d " " -f 1
- By obtaining the USER environment variable: env | grep USER | cut -d "=" -f 2
- Get login information through last → Find the current user's login information and count
last | grep -c `env | grep USER | cut -d "=" -f 2`
[PS] To display more information, you need to find:
- /var/log/wtmp.x, x ∈ [0-9]
- Refer to How to read older login info using the “last” command?——StackExchange
Last Stay Duration [This Month]#
【Last Stay: 01 hour 03 minutes】
【Obtain through last】
- Get login information through last → Find the user's login information → Match the line with the connection time in “()” format → Get the most recent one → Split by “ ( ”, “ ) ” to get the last stay duration,
- Time format is hours: minutes
- Refer to AWK - Regular Expressions——Simple Tutorial
last | grep `env | grep USER | cut -d "=" -f 2` | awk '/\(*\)/' | head -1 | cut -d "(" -f 2 | cut -d ")" -f 1
Find Famous Quotes API#
【Famous Quotes Display】
【Source: Famous Quotes——Free API】
- Up to 100 requests per day
- Request via curl: curl https://v1.alapi.cn/api/mingyan
- Return format: json
- Optional parameters: typeid [1~45]
- Randomly obtained json data is as follows:
【Use jq to process json data】
- Install using sudo apt install jq
- Use the following command
curl -s https://v1.alapi.cn/api/mingyan | jq '.data | [.content, .author]' | jq 'join("————")'
- Refer to jq tutorial (simple usage), jq manual (detailed operations)
- Also refer to Using Shell Scripts to Process JSON——Blog
- Although awk and sed commands can be used to process different json data, using the powerful jq here provides greater robustness
Find Local Daily Weather Forecast API#
【Weather Display】
【Source: wttr.in——Github】
- Can output in one line, more concise
- Custom parameters are as follows:
- Mainly displays location, weather icon, perceived temperature, and the shape of the moon at night, call the following command
curl wttr.in/\?format="%l:+%c+%t+feels+like+%f,+moon+tonight:+%m\n"
Set Warm Greetings#
【Greetings, Random Colors】
【Use figlet and lolcat to generate artistic text】
- Install using sudo apt install figlet
- [Expand font library]figlet-fonts——Github, after git clone, place all files in /usr/share/figlet/
- You can view all font demonstrations about Hey Double through showfigfonts "Hey Double"
- Figlet has many optional features, as follows:
- After pairing, choose your favorite style, my pairing: figlet -t -r Hey Double -f miniwi
- Then use lolcat to color the greeting: install using sudo apt install lolcat
- Use the following commands
figlet Hey Double -f miniwi | lolcat
figlet -t -r You\'re back -f miniwi | lolcat
Script Production [Including Color Optimization]⭐#
~/.login.sh#
- 【Key】 lies in the use of jq, awk, sed
- If curl returns unexpected results, implement some protection mechanisms
- For some boundaries, as well as array and variable operations, more exploration will be done in the future
- ⭐ Note the compatibility of zsh and bash
- In zsh: array indexing starts from 1, special characters must be escaped❗
- [PS]
- Additional features 【real-time stock data, last login time, total usage time this month】 are mentioned at the end——Appendix
- The appkey and sign for stock data need to be generated from official website
.zlogin#
- ⭐ Do not use source to call the script, but use zsh/bash based on Shell type [default bash], because
- This boot script is only for display, no need to add environment variables
- Using zsh/bash will open a child Shell to run the script, while using source runs in the current Shell, and the variables added in the script will take effect in the environment [can be viewed through set to see all locally defined environment variables]
【Discussion】Difference Between Source and Bash Script Calls#
- The results of bash and source scripts are inconsistent, the previous tests were done using bash, while the boot script is executed using source, which will call the current Shell——zsh
- Boot display as follows
- Use set -x to open script debugging, you can see the complete process
- The left side is the code, the right side is the debugging result
- You can see that the index variable has become empty!
- 【①】 It turns out that the inconsistency in the starting index of arrays between zsh and bash is the problem
- Therefore, consider making a judgment on the shell running the script
- Using ${SHELL} for judgment is not effective, in zsh, whether using source or bash points to /usr/bin/zsh
- But there is another detection method
- Refer to How to get shell to self-detect using zsh or bash——Stackoverflow
- 【Or】 you can refer to the method below, calling array elements' unique skills? Not attempted, but the above method works🆗
- Refer to Behavior of Arrays in bash scripting and zsh shell (Start Index 0 or 1?)——Stackoverflow
- 【②】 The array index issue is resolved, but other compatibility issues with zsh should also be noted
- ❗ Special characters, here the [] after jq need to be escaped
【References】
- Shell Command Substitution: Assigning the Output of a Command to a Variable——C Language Chinese Network
- $() supports nesting, backticks do not
- $() is only valid in Bash, while backticks can be used in various Shells
- Several Methods to Implement String Splitting in Shell——CSDN
- ⭐arr=(${parameter//pattern/string})
- echo args | tr "oldSpilt" "newSpilt"
- AWK Beginner's Tutorial——Ruan Yifeng
- AWK Formatted Printing——Yibai Tutorial
- Shell Source Command: Force Environment Variable Configuration File to Take Effect——C Language Chinese Network
Appendix#
Global Stock Index#
curl http://api.k780.com/\?app=finance.globalindex\&inxids=1010,1011,1013\&appkey=your_key\&sign=your_sign | jq .
Last Login Time#
- last
last | grep `env | grep USER | cut -d "=" -f 2` | awk '/\(*\)/' | head -1 | awk '{printf "%s %s %s —— %s", $4, $5, $6, $7}'
- To be improved, the cutting method is quite rigid
Total Usage Time This Month#
ac | awk '{print int($NF)}'
- ac command: displays user connection time data
- ac shows the total usage time of the user this month
- ac -d shows the daily connection time of the user this month
- Refer to Detailed Explanation of ac Command——commandnotfound
——Can Try——#
On This Day in History#
curl http://api.juheapi.com/japi/toh\?key=your_key\&v=1.0\&month=11\&day=1
- Count how many records there are
curl -s http://api.juheapi.com/japi/toh\?key=your_key\&v=1.0\&month=1\&day=1 | jq '.result | length'
- Randomly output one of them
- Generate a random number between 0 and N
$(( ${RANDOM} % ${N} ))
How Many Visitors Were Rejected#
- From the last login to now, how many failed login records
sudo lastb
- Requires sudo permission, only thought of putting the password in the script, which is unsafe
Last Login Command Statistics#
【Statistics through history】
- How many commands were entered
- Which command is your favorite
- What commands are often mistyped
Looks quite time-consuming
Reference Materials#
- To display images in the terminal, refer to termpix——Github
- Curl Usage Guide——Ruan Yifeng
- Free API Interface Collection
- NowAPI
- Getting Weather Forecast in Linux Character Interface——Zhihu
- Is there a reason why the first element of a Zsh array is indexed by 1 instead of 0?——StackExchange
- Array indexing in Bash starts from 0, while in zsh it starts from 1
- Configuring SSH Login Prompt in Linux [Static Information: Banner, motd]——Blog