Experimental Environment: Ubuntu 18.04 Remote Server + WSL2 Local Machine
Functional Requirements#
Final Outcome#
Based on the implementation of the above functions, additional features such as 【real-time stock data, last login time, total usage time this month】 were added, with a certain degree of fault tolerance 【Shell judgment, default value returned on API call failure】, and some features to try, see the end of the article 【On this day in history, rejected visitors, command statistics from last login, display images in the 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
Removing Original Boot Information#
How to remove the above information?
- With guidance from a master [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... entering each file corresponds to the login information above
- Here, motd means message of the day——daily message
- 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 a reference to 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 static message source /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 [sounds familiar]
【At this point, back to the pre-liberation state】
Preliminary Preparation#
Find the Startup Running Files#
【Using zsh startup configuration file】
Shell: zsh
- Search FILES through man zsh to view the zsh startup 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's Logins: 40 times】
【Obtained 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
- last to obtain login information → 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】
【Obtained through last】
- last to obtain login information → 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 parameter: typeid [1~45]
- Randomly obtained json data 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 use), 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 provides greater robustness
Find Local Today's Weather Forecast API#
【Weather Display】
【Source: wttr.in——Github】
- Can output in one line, more concise
- Custom parameters as follows:
- Mainly displays location, weather icon, feels-like temperature, and the shape of the moon tonight, called with 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 for Hey Double through showfigfonts "Hey Double"
- Figlet has many optional styles, as follows:
- After mixing and matching, choose your favorite style, my combination: figlet -t -r Hey Double -f miniwi
- Then use lolcat to color the greetings: 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 Creation [Including Color Optimization]⭐#
~/.login.sh#
- 【Key】 lies in the use of jq, awk, sed
- If curl returns unexpected results, implement some protective mechanisms
- For some boundaries, as well as array and variable operations, further refinement is needed in the future
- ⭐ Note the compatibility between 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】 can be seen at the end——Appendix
- The appkey and sign for stock data need to be generated from the official website
.zlogin#
- ⭐ Do not use source to call the script, but use zsh/bash based on Shell type [default bash], because
- This startup 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 startup script is executed using source, which calls the current Shell——zsh
- The startup display is as follows
- Using 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 in zsh and bash, the legendary 【array starting index】 inconsistency issue
- Therefore, consider making a judgment on the shell running the script
- Using ${SHELL} for judgment is ineffective; in zsh, whether using source or bash, it 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' special techniques? Not tried, 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 with \
【References】
- Shell Command Substitution: Assigning Command Output to Variables——C Language Chinese Network
- $() supports nesting, backticks do not
- $() is only valid in Bash, while backticks can be used in multiple Shells
- Several Methods to Implement String Splitting in Shell——CSDN
- ⭐arr=(${parameter//pattern/string})
- echo args | tr "oldSpilt" "newSpilt"
- Introduction to awk——Ruan Yifeng
- awk formatted printing——Yibai Tutorial
- Shell source command: Force the 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 splitting 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
- Guide to Using curl——Ruan Yifeng
- Free API Interface Collection
- NowAPI
- Getting Weather Forecasts 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 Prompts in Linux [Static Information: Banner, motd]——Blog