centos特有软件-邮件服务-sendmail(linux默认邮件服务器)

Linux服务器mail程序本身就是调用sendmail来进行邮件发送的,sendmail服务器提供对外的邮件发送功能。CentOS默认不能发送邮件,需要发送邮件的童鞋可以安装一个sendmail程序。

一、搭建sendmail

[root@ProxyServer ~]# yum -y install sendmail
[root@ProxyServer ~]# /etc/init.d/sendmail start
Starting sendmail:                                         [  OK  ]
Starting sm-client:                                        [  OK  ]
[root@ProxyServer ~]# chkconfig sendmail on
[root@ProxyServer ~]# man mail
......
       mailx [-BDdEFintv~] [-s subject] [-a attachment ] [-c cc-addr] [-b bcc-addr] [-r from-addr] [-h hops] [-A account]
              [-S variable[=value]] to-addr . . .
       mailx [-BDdeEHiInNRv~] [-T name] [-A account] [-S variable[=value]] -f [name]
       mailx [-BDdeEinNRv~] [-A account] [-S variable[=value]] [-u user]
......

centos7  是   systemctl  start  sendmail  不用 /etc/init.d/sendmail start
centos7   不需要  chkconfig sendmail on 这是开机启动的意思
man mail 是查看帮助文档的意思

我自己电脑测试了一下:发现 mail命令和mailx命令,都是安装了mailx才有的。所以还应该安装 yum install mailx

1、通过命令行发送邮件

cooldeMacBook-Pro:~ cool$ mail -s "这里写邮件标题" [email protected] 
这里写邮件正文
信息 
随便写
EOT
cooldeMacBook-Pro:~ cool$

第一行是输入的命令,-s表示邮件的主题,后面的[email protected]则是邮件的接收人,输入完这行命令后回车,会进入邮件正文的编写,可以输入任何文字,比如上面的三行。当邮件正文输入完成后,需要按CTRL+D结束输入。

这样本地电脑可以发送成功到指定邮箱。目标收件箱显示:邮件来自:
“cool@cooldeMacBook-Pro.local

经过测试:-s 后面的 邮件主题 可以不加 双引号,也没有问题,结果和原来一样,寄件人显示 "cool
mail -s test [email protected]

【寄件人”cool 是电脑用户名,寄件地址 cooldeMacBook-Pro.local 是主机的hostname】

cooldeMacBook-Pro:~ cool$ echo $HOSTNAME
cooldeMacBook-Pro.local

同理,centos 上操作和mac系统中一样。

因为线上服务器中我设置的hostname 是cool 【不是xxx.yyy类型】所以163邮箱服务器拒收了,系统退信。原因是邮件地址名 不规范。但是之前没有找到原因,所以在sendmail基础上索性就配置smtp 服务,用来代发送邮件。

2、使用管道进行邮件发送

cooldeMacBook-Pro:~ cool$ echo "hello,echo pip"|mail -s "subject pip" [email protected]

使用管道直接敲入这行命令即可完成邮件的发送,其中echo后的是邮件正文。

3、使用文件进行邮件发送

bikedeMacBook-Pro:~ cool$ mail -s "用文件来填写正文" [email protected] </Users/bike/Desktop/testfile.txt

4、邮件发送附件

很多情况下,我们也需要使用邮件来发送附件,在linux下使用mail命令发送附件也很简单,不过首先需要安装uuencode软件包,这个程序是对二进制文件进行编码使其适合通过邮件进行发送,直接使用centos的yum源可能找不到uuencode命令的包sharutils,我这里使用了网易Yum源。

[root@ProxyServer yum.repos.d]# yum -y install sharutils
[root@ProxyServer yum.repos.d]# uuencode CentOS6-Base-163.repo 163_yum_repo |mail -s "附件" [email protected] < /etc/passwd
[root@ProxyServer yum.repos.d]#

CentOS6-Base-163.repo 文件作为邮件的附件发送出去了。uuencode有两个参数,第一个是要发送的文件CentOS6-Base-163.repo,第二个是显示的文件名称163_yum_repo。

二、发送失败和查看邮件退信

如果提示mail: command not found

[root@ProxyServer ~]# mail -s "password" [email protected] < /etc/passwd
-bash: mail: command not found

那么就是没有安装mail命令,此时需要安装mail命令

[root@ProxyServer ~]# yum install mailx -y
[root@ProxyServer ~]# rpm -qa|grep mail
libreport-plugin-mailx-2.0.9-19.el6.x86_64
mailx-12.4-7.el6.x86_64
procmail-3.22-25.1.el6.x86_64
mailcap-2.1.31-2.el6.noarch
sendmail-8.14.4-8.el6.x86_64
[root@ProxyServer ~]#

总结来说:mailx 是 sendmail 和 Postfix mail 的基础,mail 命令 和 mailx 命令都依赖于 mailx。

输入 mail 或 mailx 命令,可以查看   /var/spool/mail/用户名文件夹(比如root)    下的所有的邮件。【注意安装sendmail软件时,不会再用户根目录下生成一个mbox文件夹mail -f mbox 命令 用来 显示当前终端 目录下mbox文件夹中的邮件。mail -f 命令默认缺省路径是:(用户根目录比如/Users/cool)/mbox  。所以只安装了sendmail软件的执行 mail -f 命令,会发现找不到目标文件夹。

mac系统下用的是Postfix mail【也就是说安装时会生成一个用户根目录下的mbox文件夹】,mail -f mbox 命令 用来 显示当前终端 目录下mbox文件夹中的邮件。mail -f 命令默认缺省路径是:(用户根目录比如/Users/cool)/mbox  但是奇怪的是 mac下mail 命令显示没有邮件,但是 /Users/cool/mbox 下有邮件。

输入 数字+回车,选择邮件列表中的某个邮件。
输入 空格,翻页查看邮件内容
输入 q +回车 退出邮箱

邮件的查看
mail          //出现& 在后台输入命令
Enter键   //查看当前邮件
+    //下一封邮件     —   //上一封邮件
d 数字  //删除它几号信件
s 文件名  //将信件保存为文件
r //回信  q  //退出

看下文,邮件退信的原因是:550 MI:IMF

•550 MI:IMF 发信人电子邮件地址不合规范。
请参考http://www.rfc-editor.org/关于电子邮件规范的定义;
参考帮助网站:
http://help.163.com/09/1224/17/5RAJ4LMH00753VB8.html

退信全文:

[root@superguy ~]# mail
Heirloom Mail version 12.5 7/5/10.  Type ? for help.
"/var/spool/mail/root": 12 messages 3 unread
    1 Mail Delivery Subsys  Sat Sep 29 07:27  73/2143  "Returned mail: see tr"
    2 Mail Delivery Subsys  Sat Sep 29 07:27  76/2692  "Returned mail: see tr"
    3 Mail Delivery Subsys  Sat Sep 29 07:27  76/2693  "Returned mail: see tr"
    4 Mail Delivery Subsys  Sat Sep 29 07:27  72/2537  "Returned mail: see tr"
    5 Mail Delivery Subsys  Sat Sep 29 07:27  71/2637  "Returned mail: see tr"
    6 Mail Delivery Subsys  Sat Sep 29 07:27  71/2637  "Returned mail: see tr"
>U  7 Mail Delivery Subsys  Sat Sep 29 07:27  70/2554  "Returned mail: see tr"
 U  8 Mail Delivery Subsys  Sat Sep 29 07:27  71/2636  "Returned mail: see tr"
 U  9 Mail Delivery Subsys  Sat Sep 29 07:27  71/2636  "Returned mail: see tr"
   10 Mail Delivery Subsys  Sat Sep 29 07:28  72/2633  "Returned mail: see tr"
   11 Mail Delivery Subsys  Sat Sep 29 08:16 103/4273  "Returned mail: see tr"
   12 Mail Delivery Subsys  Sat Sep 29 14:01 103/4259  "Returned mail: see tr"
& 7
Message  7:
From MAILER-DAEMON@superguy  Sat Sep 29 07:27:45 2018
Return-Path: <MAILER-DAEMON@superguy>
Date: Sat, 29 Sep 2018 07:27:45 GMT
From: Mail Delivery Subsystem <MAILER-DAEMON@superguy>
To: <root@superguy>
Content-Type: multipart/report; report-type=delivery-status;
	boundary="w8T7Rjim011448.1538206065/superguy"
Subject: Returned mail: see transcript for details
Auto-Submitted: auto-generated (failure)
Status: RO

Part 1:

The original message was received at Sat, 29 Sep 2018 07:27:40 GMT
from localhost [127.0.0.1]

   ----- The following addresses had permanent fatal errors -----
<[email protected]>
    (reason: 550 MI:IMF 163 mx14,QMCowAB3utduKa9bdw4FGw--.17130S3 1538206064 htt
p://mail.163.com/help/help_spam_16.htm?ip=118.118.118.118&hostid=mx14&time=153820
6064)

   ----- Transcript of session follows -----
... while talking to 163mx01.mxmail.netease.com.:
>>> MAIL From:<root@superguy> SIZE=617
<<< 550 MI:IMF 163 mx14,QMCowAB3utduKa9bdw4FGw--.17130S3 1538206064 http://mail.
163.com/help/help_spam_16.htm?ip=118.118.118.118&hostid=mx14&time=1538206064
554 5.0.0 Service unavailable

Part 2:
Content-Type: message/delivery-status


Part 3:
Content-Type: message/rfc822

From root@superguy Sat Sep 29 07:27:40 2018
Return-Path: <root@superguy>
From: root <root@superguy>
Date: Sat, 29 Sep 2018 07:22:57 +0000
To: [email protected]
Subject: test
User-Agent: Heirloom mailx 12.5 7/5/10
Content-Type: text/plain; charset=us-ascii

hello test
&

解决163邮箱退信办法,修改hostname,因为邮件地址是根据hostname来的,hostname应该改为 xxx.yyy

三、smtp邮件配置

其实这里用到的是mailx软件,mailx软件是在安装sendmail软件时,有可能已经自动下载了,有可能还没下载。

bin/mail会默认使用本地sendmail发送邮件,这样要求本地的机器必须安装和启动Sendmail服务,而通过修改配置文件/etc/mail.rc(/etc/nail.rc)可以使用外部SMTP服务器,可以达到不使用sendmail而用外部的smtp服务器发送邮件的目的。

不用管posix mail 和 sendmail ,只要配置好smtp后,就可以直接用mail 命令行发邮件了。发件人就是下面配置好的user。

[root@ProxyServer ~]# vim /etc/mail.rc          #文末添加以下
 set [email protected] 
 set smtp=smtp.51cto.com
 set [email protected] 
 set smtp-auth-password=51cto 
 set smtp-auth=login
[root@ProxyServer ~]# source /etc/mail.rc
[root@ProxyServer ~]# mail -s "51cto" 15001*****@139.com < /etc/passwd

from:发送的邮件地址(真实地址,我测试时候直接写justin发送邮件失败),对方显示的发件人
smtp:发生的外部smtp服务器的地址
smtp-auth-user:外部smtp服务器认证的用户名
smtp-auth-password:外部smtp服务器认证的用户密码(我测试过用邮箱登录密码OK)
smtp-auth:邮件认证的方式

四、邮箱命令行介绍

-b<地址>:指定密件副本的收信人地址;
-c<地址>:指定副本的收信人地址;
-f<邮件文件>:读取指定邮件文件中的邮件;
-i:不显示终端发出的信息;
-I:使用互动模式;
-n:程序使用时,不使用mail.rc文件中的设置;
-N:阅读邮件时,不显示邮件的标题;
-s<邮件主题>:指定邮件的主题;
-u<用户帐号>:读取指定用户的邮件;
-v:执行时,显示详细的信息。

1、使用sendmail -bp 或者 mailq 可以查看到邮件发送队列,里边会列出有几个邮件等待发送。

mailq 查看队列Postfix mail 会报错因为服务没有开启,需要 sudo postfix status ,sudo postfix start 

[root@CHINFO3 mqueue]# mailq
		/var/spool/mqueue (5 requests)
-----Q-ID----- --Size-- -----Q-Time----- ------------Sender/Recipient-----------
tB36BqUi005128     1716 Thu Dec  3 14:11 <infa@chinfo3>
                 (Deferred: mx.263.net.: No route to host)
					 <[email protected]>
tB21TicN013397      415 Wed Dec  2 09:29 <infa@chinfo3>
                 (Deferred: mx.263.net.: No route to host)
					 <[email protected]>
......
[root@CHINFO3 mqueue]# sendmail -bp
		/var/spool/mqueue (5 requests)
-----Q-ID----- --Size-- -----Q-Time----- ------------Sender/Recipient-----------
tB36BqUi005128*    1716 Thu Dec  3 14:11 <infa@chinfo3>
                 (Deferred: mx.263.net.: No route to host)
					 <[email protected]>
tB21TicN013397      415 Wed Dec  2 09:29 <infa@chinfo3>
                 (Deferred: mx.263.net.: No route to host)
					 <[email protected]>
......
[root@CHINFO3 mqueue]#

邮件队列的文件都保存在 /var/spool/mqueue/ 文件夹内,查看此文件夹时,可以看到邮件队列内的邮件:【命令行 pwd  是输出当前目录】

[root@CHINFO3 mqueue]# pwd
/var/spool/mqueue
[root@CHINFO3 mqueue]# ls
dftB111d4Q031164  dftB213omV012806  dftB36BqUi005128  qftB117J4b006323  qftB21TicN013397
dftB117J4b006323  dftB21TicN013397  qftB111d4Q031164  qftB213omV012806  qftB36BqUi005128
[root@CHINFO3 mqueue]#

如果需要删除队列,直接清空该文件夹即可:【当前在这个 /var/spool/mqueue目录】

[root@CHINFO3 mqueue]# pwd
/var/spool/mqueue
[root@CHINFO3 mqueue]# ls
dftB111d4Q031164  dftB213omV012806  dftB36BqUi005128  qftB117J4b006323  qftB21TicN013397
dftB117J4b006323  dftB21TicN013397  qftB111d4Q031164  qftB213omV012806  qftB36BqUi005128
[root@CHINFO3 mqueue]# rm -f *
[root@CHINFO3 mqueue]# ls
[root@CHINFO3 mqueue]# mailq
/var/spool/mqueue is empty
		Total requests: 0
[root@CHINFO3 mqueue]#

2、tail  /var/log/maillog   查看日志 或者如下 

[root@CHINFO3 ~]# cd /var/log/
[root@CHINFO3 log]# cat mail
mail/      maillog    maillog.1  maillog.2  maillog.3  maillog.4  
[root@CHINFO3 log]# cat mail

五、SendMail服务启动慢总结

在 CentOS release 6.6 上启动sendmail服务时发现服务启动过程非常慢,基本上要耗费3分多钟。有点纳闷:什么原因导致sendmail启动这么慢?搜索了这方面的一些资料,结合自己的理解,把它梳理一遍。权当笔记。

[root@MySQL-T01 bin]# service sendmail stop
Shutting down sm-client: [ OK ]
Shutting down sendmail: [ OK ]
[root@MySQL-T01 bin]# date 
Wed Aug 5 09:11:00 UTC 2015
[root@MySQL-T01 bin]# service sendmail start
Starting sendmail: [ OK ]
Starting sm-client: [ OK ]
[root@MySQL-T01 bin]# date
Wed Aug 5 09:14:53 UTC 2015

如上所示,sendmail服务的启动整整需要花费3分多钟。因为Starting sendmail、Starting sm-client这两步check需要查询你设置的主机名的A记录或反向域名记录,由于全球9台DNS根系统都在美国,这个时候会去查询本机主机名对应的dns A记录。查询可能会非常的慢.

通常的域名解析是指A记录解析,即主机记录解析,就是指把域名解析到虚拟主机的过程;又称IP指向,用户可以在此设置子域名并指向到自己的目标主机地址上,从而实现通过域名找到服务器。

让sendmial绕过查询远程主机,这里给出一种最简单的方法,给主机设置一个别名。

/etc/hosts原始配置

[root@MySQL-T01 bin]# more /etc/hosts
10.20.251.45 MySQL-T01 localhost
127.0.0.1   localhost  localhost.localdomain localhost4 localhost4.localdomain4
::1         localhost  localhost.localdomain localhost6 localhost6.localdomain6

/etc/hosts修改配置

[root@MySQL-T01 bin]# vi /etc/hosts
10.20.251.45 MySQL-T01 localhost
127.0.0.1   localhost localhost.localdomain MySQL-T01
::1         localhost localhost.localdomain localhost6 localhost6.localdomain6

修改完成后,关闭sendmail服务,启动sendmail服务非常快,只要一两秒的样子。

[root@MySQL-T01 bin]# service sendmail stop
Shutting down sm-client: [  OK  ]
Shutting down sendmail: [  OK  ]
[root@MySQL-T01 bin]# service sendmail start
Starting sendmail: [  OK  ]
Starting sm-client: [  OK  ]
[root@MySQL-T01 bin]#

六、使用mailx465端口发送邮件

前面提到的邮件发送都是 25端口 发送的,在一些云服务器中为了防止邮件滥发,往往都对25端口做了限制,所以此时就使用到加密的465端口了,本篇文章以qq邮箱为例来配置mailx,通过465端口发送邮件。

1、关闭其它的邮件工具

下面是两种邮件服务器:

service sendmail stop
chkconfig sendmail off
service postfix stop
chkconfig postfix off

2、安装mailx

现在安装sendmail已经自动安装mailx了。

yum install mailx

3、在邮箱网站中开启smtp功能

开启后会得到一个授权码,这个授权码可以代替邮箱密码(自行去邮箱开启),如果用邮箱密码也没有问题。

4、请求数字证书

(这里用的163邮箱,所以向163请求证书)

mkdir -p /root/.certs/
echo -n | openssl s_client -connect smtp.163.com:465 | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' > ~/.certs/163.crt
certutil -A -n "GeoTrust SSL CA" -t "C,," -d ~/.certs -i ~/.certs/163.crt
certutil -A -n "GeoTrust Global CA" -t "C,," -d ~/.certs -i ~/.certs/163.crt
certutil -A -n "GeoTrust SSL CA - G3" -t "Pu,Pu,Pu" -d ~/.certs/ -i ~/.certs/163.crt
certutil -L -d /root/.certs

最后会在 /root/.certs/   文件夹下面:生成4个文件:

### 我用163服务器 做测试通过了,证书文件夹下面有如下4个 文件  
163.crt  cert8.db   key3.db secmod.db

5、配置/etc/mail.rc

set [email protected] #之前设置好的邮箱地址
set smtp=smtps://smtp.163.com:465 #邮件服务器
set [email protected] #之前设置好的邮箱地址
set smtp-auth-password=xxxx #授权码
set smtp-auth=login #默认login即可
set ssl-verify=ignore #ssl认证方式
set nss-config-dir=/root/.certs #证书所在目录

smtp-auth-password:外部smtp服务器认证的用户密码(我测试过用邮箱登录密码也OK)【在前面提到的第三步在网站邮箱中开启smtp,就可以获取授权码】

6、重新加载配置

source /etc/mail.rc

7、发送邮件测试

echo "邮件正文" | mail -s "邮件主题" [email protected]

七、删除mail邮件

方法一:使用mail命令,然后在 & 提示符下使用 d 命令(Delete),批量删除邮件,例如删除1~53邮件:

  # mail
  & d 1-53

方法二:删除全部系统邮件

  # > /var/spool/mail/root    or  cat /dev/null > /var/spool/mail/root

  或者

  # echo "d *" |mail -N

参考:

http://blog.51cto.com/ityunwei2017/1713425
https://www.cnblogs.com/kerrycode/p/4717498.html

Centos使用mailx465端口发送邮件

补充:MUA、MDA、MTA
http://blog.51cto.com/20101218/701794
https://www.cnblogs.com/horizonli/p/5591438.html

bash-运算-脚本中获取到命令执行结果值

#!/bin/bash

# 反引号 就是将运行的 命令行结果 赋值给 result 
 result=`mysqladmin -u root -pKitty521! ping`

# result=`/usr/bin/mysqladmin ping`

# 单引号 ,双引号 都可以 保存 普通 字符串 变量
expected='mysqld is alive'

if [[ "$result" = "$expected" ]]

then

echo "mysqld is alive"

else

echo "It's dead - restart mysql"

fi

bash中:单引号与双引号的区别

单引号中是原始字符串
双引号可以对特殊字符进行扩展,如
a=bcdef
echo “$a” #双引号将进行变量扩展 ,输出bcdef
echo ‘$a’ #单引号直接输出$a

bash-文件-linux命令行输出重定向

无论是shell 还是 dos ,用法是一样的。

一共有4个输出到文件的命令,现以jar命令打war包举例说明:

命令 说明 举例
> 正常输出覆盖指定文件  jar -xvf my.war @select.txt  > output.txt
2> 正常输出尾部追加到指定文件  jar -xvf my.war @select.txt  2> output.txt
>> 异常输出覆盖指定文件  jar -xvf my.war @select.txt  >> error.txt
2>> 异常输出尾部追加到指定文件  jar -xvf my.war @select.txt  2>> error.txt

 

# 我这里用到 的 重定向 测试
netstat -r >/Users/cool/Desktop/test.txt

 

bash-概述-bash和shell的区别

Linux 中的 shell 有很多类型,其中最常用的几种是: Bourne shell (sh)、C shell (csh) 和 Korn shell (ksh), 各有优缺点。Bourne shell 是 UNIX 最初使用的 shell,并且在每种 UNIX 上都可以使用, 在 shell 编程方面相当优秀,但在处理与用户的交互方面做得不如其他几种shell。Linux 操作系统缺省的 shell 是Bourne Again shell,它是 Bourne shell 的扩展,简称 Bash,与 Bourne shell 完全向后兼容,并且在Bourne shell 的基础上增加、增强了很多特性。Bash放在/bin/bash中,它有许多特色,可以提供如命令补全、命令编辑和命令历史表等功能,它还包含了很多 C shell 和 Korn shell 中的优点,有灵活和强大的编程接口,同时又有很友好的用户界面。

GNU/Linux 操作系统中的 /bin/sh 本是 bash (Bourne-Again Shell) 的符号链接,但鉴于 bash 过于复杂,有人把 ash 从 NetBSD 移植到 Linux 并更名为 dash (Debian Almquist Shell),并建议将 /bin/sh 指向它,以获得更快的脚本执行速度。Dash Shell 比 Bash Shell 小的多,符合POSIX标准。

Ubuntu继承了Debian,所以从Ubuntu 6.10开始默认是Dash Shell。

luotaijia@ubuntu:~$ ls -l /bin/sh /bin/bash 
-rwxr-xr-x 1 root root 801808 2010-08-11 03:58 /bin/bash 
lrwxrwxrwx 1 root root 4 2012-11-28 08:06 /bin/sh -> dash

在centos中,
1、/bin 是超链接 指向 /usr/bin
2、/bin/sh 【真实路径/usr/bin/sh】  是超链接 指向  /bin/bash 【真实路径/usr/bin/bash】

[cool@localhost /]$ ls -l /bin/sh&nbsp; 
lrwxrwxrwx. 1 root root 4 Jun 26 03:58&nbsp;/bin/sh -> bash
[cool@localhost /]$ ls -l /bin/bash
-rwxr-xr-x. 1 root root 964544 Apr 11 08:06&nbsp;/bin/bash

应该说, /bin/sh 与 /bin/bash 虽然大体上没什么区别, 但仍存在不同的标准. 标记为 “#!/bin/sh” 的脚本不应使用任何 POSIX 没有规定的特性 (如 let 等命令, 但 “#!/bin/bash” 可以). Debian 曾经采用 /bin/bash 更改 /bin/dash,目的使用更少的磁盘空间、提供较少的功能、获取更快的速度。但是后来经过 shell 脚本测试存在运行问题。因为原先在 bash shell 下可以运行的 shell script (shell 脚本),在 /bin/sh 下还是会出现一些意想不到的问题,不是100%的兼用。

Linux中的shell有多种类型,其中最常用的几种是Bourne shell(sh)、C shell(csh)和Korn shell(ksh)。三种shell各有优缺点。
Bourne shell是UNIX最初使用的shell,并且在每种UNIX上都可以使用。Bourne shell在shell编程方面相当优秀,但在处理与用户的交互方面做得不如其他几种shell。

Linux操作系统缺省的shell是Bourne Again shell,它是Bourne shell的扩展,简称Bash,与Bourne shell完全向后兼容,并且在Bourne shell的基础上增加、增强了很多特性。Bash放在/bin/bash中,它有许多特色,可以提供如命令补全、命令编辑和命令历史表等功能,它还包含了很多C shell和Korn shell中的优点,有灵活和强大的编程接口,同时又有很友好的用户界面。
GNU/Linux 操作系统中的 /bin/sh 是 bash(Bourne-Again Shell)的符号链接,
但鉴于 bash 过于复杂,有人把 ash 从 NetBSD 移植到 Linux 并更名为 dash(Debian Almquist Shell),并建议将 /bin/sh 指向它,以获得更快的脚本执行速度。Ubuntu 号称自从他们在 6.10 版里这样做了以后,系统启动速度有了明显的提升。Debian 计划在下一个发行版(代号 lenny)中也将 dash 作为默认的 /bin/sh。

 

 

centos7初装系统-启动级别分类

在Linux中有7种启动级别:修改系统启动级别:修改系统默认启动到3多用户状态,在Linux中有7种启动级别,默认是X-Window,像是Windows的窗口模式,而Linux的操作和配置一般都采用输入命令的方式来完成,需要更改默认启动级别才可以实现。
第1步:以管理员身份进入Linux,修改文件:/etc/inittab文件。
第2步:找到“id:5:initdefault:”,其中的5就是X-Window,为默认运行级别,把5改为3即可。
7总运行级别介绍如下:
# 0 - halt (Do NOT set initdefault to this)
# 1 - Single user mode
# 2 - Multiuser, without NFS (The same as 3, if you do not have networking)
# 3 - Full multiuser mode
# 4 - unused
# 5 - X11
# 6 - reboot (Do NOT set initdefault to this)
各个运行级的详细解释:
0 为停机,机器关闭。
1 为单用户模式,就像Win9x下的安全模式类似。
2 为多用户模式,但是没有NFS支持。
3 为完整的多用户模式,是标准的运行级。
4 一般不用,在一些特殊情况下可以用它来做一些事情。例如在笔记本电脑的电池用尽时,可以切换到这个模式来做一些设置。
5 就是X11,进到X Window系统了。
6 为重启,运行init 6机器就会重启。
0和6一般不用;
运行startx可启动到级别5。

最新的 centos7 中,配置 文档 里面有 说明,需要 用 命令行 配置:
systemctl set-default graphical.target

centos7初装系统-cannot find a valid baseurl for repo:base/7/x86_64

安装CentOS7文字界面版后,无法联网,用yum安装软件提示 cannot find a valid baseurl for repo:base/7/x86_64 的解决方法

*无法联网的明显表现会有:

1、yum install出现 Error: cannot find a valid baseurl or repo:base

2、ping host会提示unknown host

 

方法一、

1、打开 vi /etc/sysconfig/network-scripts/ifcfg-eth0(每个机子都可能不一样,但格式会是“ifcfg-eth数字”),把ONBOOT=no,改为ONBOOT=yes

2、重启网络:service network restart

方法二、

1、打开 vi /etc/resolv.conf,增加 nameserver 8.8.8.8

2、重启网络: service network restart

来自:https://www.cnblogs.com/hopkings/p/6140654.html

 

我这边的文件名字是     /etc/sysconfig/network-scripts/ifcfg-enp0s3

centos初装系统-安全性加固

转载自:https://www.linode.com/docs/security/securing-your-server/

In the Getting Started guide, you learned how to deploy a Linux distribution, boot your Linode and perform basic administrative tasks. Now it’s time to harden your Linode against unauthorized access.

Update Your System–FrequentlyPermalink

Keeping your software up to date is the single biggest security precaution you can take for any operating system. Software updates range from critical vulnerability patches to minor bug fixes, and many software vulnerabilities are actually patched by the time they become public.

Automatic Security UpdatesPermalink

There are arguments for and against automatic updates on servers. Fedora’s Wikihas a good breakdown of the pros and cons, but the risk of automatic updates will be minimal if you limit them to security updates. Not all package managers make that easy or possible, though.

The practicality of automatic updates is something you must judge for yourself because it comes down to what you do with your Linode. Bear in mind that automatic updates apply only to packages sourced from repositories, not self-compiled applications. You may find it worthwhile to have a test environment that replicates your production server. Updates can be applied there and reviewed for issues before being applied to the live environment.

Add a Limited User AccountPermalink

Up to this point, you have accessed your Linode as the root user, which has unlimited privileges and can execute any command–even one that could accidentally disrupt your server. We recommend creating a limited user account and using that at all times. Administrative tasks will be done using sudo to temporarily elevate your limited user’s privileges so you can administer your server.

Note

Not all Linux distributions include sudo on the system by default, but all the images provided by Linode have sudo in their package repositories. If you get the output sudo: command not found, install sudo before continuing.

To add a new user, first log in to your Linode via SSH.

CentOS / FedoraPermalink

  1. Create the user, replacing example_user with your desired username, and assign a password:
    useradd example_user && passwd example_user
    
  2. Add the user to the wheel group for sudo privileges:
    usermod -aG wheel example_user
    

    Caution

    In CentOS 6 a wheel group is disabled by default for sudo access. You must to configure it manually. Type from root: /usr/sbin/visudo. Then find the line # %wheeland uncomment this line. To began typing in vi, press a. To save and exit press Escape, then type :w(press enter), :q(press enter)

UbuntuPermalink

  1. Create the user, replacing example_user with your desired username. You’ll then be asked to assign the user a password:
    adduser example_user
    
  2. Add the user to the sudo group so you’ll have administrative privileges:
    adduser example_user sudo
    

DebianPermalink

  1. Debian does not include sudo by default so it must be installed:
    apt install sudo
    
  2. Create the user, replacing example_user with your desired username. You’ll then be asked to assign the user a password:
    adduser example_user
    
  3. Add the user to the sudo group so you’ll have administrative privileges:
    adduser example_user sudo
    
  4. After creating your limited user, disconnect from your Linode:
    exit
    
  5. Log back in as your new user. Replace example_user with your username, and the example IP address with your Linode’s IP address:
    ssh [email protected]
    

Now you can administer your Linode from your new user account instead of root. Nearly all superuser commands can be executed with sudo (example: sudo iptables -L -nv) and those commands will be logged to /var/log/auth.log.

Harden SSH AccessPermalink

By default, password authentication is used to connect to your Linode via SSH. A cryptographic key-pair is more secure because a private key takes the place of a password, which is generally much more difficult to brute-force. In this section we’ll create a key-pair and configure the Linode to not accept passwords for SSH logins.

Create an Authentication Key-pairPermalink

  1. This is done on your local computer, not your Linode, and will create a 4096-bit RSA key-pair. During creation, you will be given the option to encrypt the private key with a passphrase. This means that it cannot be used without entering the passphrase, unless you save it to your local desktop’s keychain manager. We suggest you use the key-pair with a passphrase, but you can leave this field blank if you don’t want to use one.Linux / OS X

    Caution

    If you’ve already created an RSA key-pair, this command will overwrite it, potentially locking you out of other systems. If you’ve already created a key-pair, skip this step. To check for existing keys, run ls ~/.ssh/id_rsa*.
    ssh-keygen -b 4096
    

    Press Enter to use the default names id_rsa and id_rsa.pub in /home/your_username/.ssh before entering your passphrase.

    Windows

    This can be done using PuTTY as outlined in our guide: Use Public Key Authentication with SSH.

  2. Upload the public key to your Linode. Replace example_user with the name of the user you plan to administer the server as, and 203.0.113.10 with your Linode’s IP address.LinuxFrom your local computer:
    ssh-copy-id [email protected]
    

    OS X

    On your Linode (while signed in as your limited user):

    mkdir -p ~/.ssh && sudo chmod -R 700 ~/.ssh/
    

    From your local computer:

    scp ~/.ssh/id_rsa.pub [email protected]:~/.ssh/authorized_keys
    

    Note

    ssh-copy-id is available in Homebrew if you prefer it over SCP. Install with brew install ssh-copy-id.

    Windows

    • Option 1: This can be done using WinSCP. In the login window, enter your Linode’s public IP address as the hostname, and your non-root username and password. Click Login to connect.Once WinSCP has connected, you’ll see two main sections. The section on the left shows files on your local computer and the section on the right shows files on your Linode. Using the file explorer on the left, navigate to the file where you’ve saved your public key, select the public key file, and click Upload in the toolbar above.You’ll be prompted to enter a path where you’d like to place the file on your Linode. Upload the file to /home/example_user/.ssh/authorized_keys, replacing example_user with your username.
    • Option 2: Copy the public key directly from the PuTTY key generator into the terminal emulator connected to your Linode (as a non-root user):
      mkdir ~/.ssh; nano ~/.ssh/authorized_keys
      

      The above command will open a blank file called authorized_keys in a text editor. Copy the public key into the text file, making sure it is copied as a single line exactly as it was generated by PuTTY. Press CTRL+X, then Y, then Enter to save the file.

    Finally, you’ll want to set permissions for the public key directory and the key file itself:

    sudo chmod 700 -R ~/.ssh && chmod 600 ~/.ssh/authorized_keys
    

    These commands provide an extra layer of security by preventing other users from accessing the public key directory as well as the file itself. For more information on how this works, see our guide on how to modify file permissions.

  3. Now exit and log back into your Linode. If you specified a passphrase for your private key, you’ll need to enter it.

SSH Daemon OptionsPermalink

  1. Disallow root logins over SSH. This requires all SSH connections be by non-root users. Once a limited user account is connected, administrative privileges are accessible either by using sudo or changing to a root shell using su -.
    /etc/ssh/sshd_config
    # Authentication:
    ...
    PermitRootLogin no
  2. Disable SSH password authentication. This requires all users connecting via SSH to use key authentication. Depending on the Linux distribution, the line PasswordAuthentication may need to be added, or uncommented by removing the leading #.
    /etc/ssh/sshd_config
    # Change to no to disable tunnelled clear text passwords
    PasswordAuthentication no

    Note

    You may want to leave password authentication enabled if you connect to your Linode from many different computers. This will allow you to authenticate with a password instead of generating and uploading a key-pair for every device.
  3. Listen on only one internet protocol. The SSH daemon listens for incoming connections over both IPv4 and IPv6 by default. Unless you need to SSH into your Linode using both protocols, disable whichever you do not need. This does not disable the protocol system-wide, it is only for the SSH daemon.Use the option:
    • AddressFamily inet to listen only on IPv4.
    • AddressFamily inet6 to listen only on IPv6.

    The AddressFamily option is usually not in the sshd_config file by default. Add it to the end of the file:

    echo 'AddressFamily inet' | sudo tee -a /etc/ssh/sshd_config
    
  4. Restart the SSH service to load the new configuration.If you’re using a Linux distribution which uses systemd (CentOS 7, Debian 8, Fedora, Ubuntu 15.10+)
    sudo systemctl restart sshd
    

    If your init system is SystemV or Upstart (CentOS 6, Debian 7, Ubuntu 14.04):

    sudo service ssh restart
    

Use Fail2Ban for SSH Login ProtectionPermalink

Fail2Ban is an application that bans IP addresses from logging into your server after too many failed login attempts. Since legitimate logins usually take no more than three tries to succeed (and with SSH keys, no more than one), a server being spammed with unsuccessful logins indicates attempted malicious access.

Fail2Ban can monitor a variety of protocols including SSH, HTTP, and SMTP. By default, Fail2Ban monitors SSH only, and is a helpful security deterrent for any server since the SSH daemon is usually configured to run constantly and listen for connections from any remote IP address.

For complete instructions on installing and configuring Fail2Ban, see our guide: Securing Your Server with Fail2ban.

Remove Unused Network-Facing ServicesPermalink

Most Linux distributions install with running network services which listen for incoming connections from the internet, the loopback interface, or a combination of both. Network-facing services which are not needed should be removed from the system to reduce the attack surface of both running processes and installed packages.

Determine Running ServicesPermalink

To see your Linode’s running network services:

sudo ss -atpu

The following is an example of the output given by ss, and shows that the SSH daemon (sshd) is listening and connected. Note that because distributions run different services by default, your output will differ.

 Netid State Recv-Q Send-Q Local Address:Port Peer Address:Port tcp LISTEN 0 128 *:ssh *:* users:(("sshd",pid=3675,fd=3)) tcp ESTAB 0 208 203.0.113.1:ssh 198.51.100.2:54820 users:(("sshd",pid=3698,fd=3)) tcp LISTEN 0 128 :::ssh :::* users:(("sshd",pid=3675,fd=4)) 

TCPPermalink

See the Peer Address:Port column of the ss readout. The process sshd is listening on *:*, which translates into any incoming IPv4 address to any port, and over any network interface. The next line shows an established SSH connection from IP address 198.51.100.2 via ephemeral port 54820. The last line, :::*denotes the sshd process listening for any incoming SSH connections over IPv6 to any port, and again over any network interface.

UDPPermalink

UDP sockets are stateless, meaning they are either open or closed and every process’s connection is independent of those which occurred before and after. This is in contrast to TCP connection states such as LISTEN, ESTABLISHED and CLOSE_WAIT. The ss output above shows no UDP connections.

Determine Which Services to RemovePermalink

A basic TCP and UDP nmap scan of your Linode without a firewall enabled would show SSH and possibly other services listening for incoming connections. By configuring a firewall you can filter those ports to your requirements. Ideally, the unused services should be disabled.

You will likely be administering your server primarily through an SSH connection, so that service needs to stay. As mentioned above, RSA keys and Fail2Ban can help protect SSH. System services like chronyd, systemd-resolved, and dnsmasqare usually listening on localhost and only occasionally contacting the outside world. Services like this are part of your operating system and will cause problems if removed and not properly substituted.

However, some services are unnecessary and should be removed unless you have a specific need for them. Some examples could be Exim, Apache and RPC.

Uninstall the Listening ServicesPermalink

How to remove the offending packages will differ depending on your distribution’s package manager.

Arch

sudo pacman -Rs package_name

CentOS

sudo yum remove package_name

Debian / Ubuntu

sudo apt purge package_name

Fedora

sudo dnf remove package_name

Run ss -atup again to verify that the unwanted services are no longer running.

Configure a FirewallPermalink

Using a firewall to block unwanted inbound traffic to your Linode provides a highly effective security layer. By being very specific about the traffic you allow in, you can prevent intrusions and network mapping. A best practice is to allow only the traffic you need, and deny everything else. See our documentation on some of the most common firewall applications:

  • Iptables is the controller for netfilter, the Linux kernel’s packet filtering framework. Iptables is included in most Linux distributions by default.
  • FirewallD is the iptables controller available for the CentOS / Fedora family of distributions.
  • UFW provides an iptables frontend for Debian and Ubuntu.

Next StepsPermalink

These are the most basic steps to harden any Linux server, but further security layers will depend on its intended use. Additional techniques can include application configurations, using intrusion detection or installing a form of access control.

Now you can begin setting up your Linode for any purpose you choose. We have a library of documentation to assist you with a variety of topics ranging from migration from shared hosting to enabling two-factor authentication to hosting a website.

See Also

centos初装系统-修改timezone

It may be better to use the same timezone which a majority of your users are located in, or that you live in to make log file timestamps more sensible.

Debian / Ubuntu

[bash]dpkg-reconfigure tzdata[/bash]

Arch Linux and CentOS 7

View the list of available time zones.

[bash]timedatectl list-timezones[/bash]

Use the Up, Down, Page Up and Page Down keys to navigate. Find the time zone which you want. Remember it, write it down or copy it as a mouse selection. Then press q to exit the list.

To set the time zone:

[bash]timedatectl set-timezone ‘America/New_York'[/bash]

Gentoo

View the list of available time zones.

[bash]ls /usr/share/zoneinfo[/bash]

Write the selected time zone to the /etc/timezone file.

Example (for Eastern Standard Time):

[bash]echo "EST" > /etc/timezone[/bash]

Configure the sys-libs/timezone-data package, which will set /etc/localtimeappropriately.

[bash]emerge –config sys-libs/timezone-data[/bash]

Check the Time

View the current date and time according to your server.

[bash]date[/bash]

The output should look similar to: Thu Feb 16 12:17:52 EST 2012.

 

转载自:https://www.linode.com/docs/getting-started/