內容選單標籤

2020年2月24日 星期一

CentOS8 指令練習與網路管理

此篇已經重新謄錄完成!!
可以作廢。


-------------------------------------------------------------

//系統版本
CentOS8  Linux 8 ( Core )

// 4.18.0 核心版本    147 修正次數   x86 相容電腦 61 bit
Kernel 4.18.0-147.5.1.e18_1.x86_64 on an x86_64




// # 最高權限管理者   $ 一班使用者   root 使用者   CentOS8 主機名   ~ 使用者家目錄
[root@CentOS8 ~]#



// show who is logged on
# who
root     pts/1        2020-03-21 15:33 (192.168.2.100)



//  Show who is logged on and what they are doing
# w
 15:42:45 up  1:20,  2 users,  load average: 0.00, 0.00, 0.00
USER     TTY      FROM             LOGIN@   IDLE   JCPU   PCPU WHAT
root     pts/1    192.168.2.100    15:33    0.00s  0.06s  0.03s w




// 關機馬上 halt
# shutdown -h now

// 關機10分鐘後
# shutdown -h 10

//重開機 reboot
# shutdown -r

#reboot




// print name of current/working directory
# pwd
/root

// 列出 檔案系統 根目錄 下
# ls /
bin   dev  home  lib64  mnt  proc  run   srv  tmp          usr
boot  etc  lib   media  opt  root  sbin  sys  ubstituteqq  var

// .. 上一層目錄,目前在 /root
# ls ..
bin   dev  home  lib64  mnt  proc  run   srv  tmp          usr
boot  etc  lib   media  opt  root  sbin  sys  ubstituteqq  var

// . 目前所在目錄,目前在 /root ,同 # ls
# ls .


//list directory contents
//Change  the current directory to dir
# cd /home
[root@CentOS8 home]#





//print system information
// -s, --kernel-name   -n, --nodename   -r, --kernel-release
# uname -snr
Linux Ku.CentOS8 4.18.0-147.el8.x86_64




# date
四  3月 26 10:50:07 CST 2020



# echo $LANG
zh_TW.UTF-8

# locale
LANG=zh_TW.UTF-8
...



# vi /etc/hostname
Ku.CentOS8

# hostnamectl set-hostname Ku.CentOS8.chehjh
# hostnamectl
   Static hostname: Ku.CentOS8.chehjh
...






-------------------------------------------------------------cp, mv, rm

//copy files and directories
// . 目前目錄下
# cp /etc/yum.conf .
# ls
anaconda-ks.cfg  yum.conf
[root@centos8 ~]# pwd
/root


//--recursive
# cp -r /etc/ssh .
# ls
anaconda-ks.cfg  ssh



// move (rename) files
# mv yum.conf aa.conf
# ls
aa.conf  anaconda-ks.cfg



//remove files or directories
# rm aa.conf
rm:是否移除普通檔案'aa.conf'? y

// --recursive   --force
# rm -rf ssh







-------------------------------------- touch, cat, more, less, head, tail

// concatenate files and print on the standard output
//--number
# cat -n /var/log/messages
...
2976  Mar 28 17:04:57 centos8 systemd[1]: Starting Cleanup of Temporary Directories...
2977  Mar 28 17:04:57 centos8 systemd[1]: Started Cleanup of Temporary Directories.

// 產生 test.txt , > 將輸入文字寫入 test.txt 中
# cat > test.txt
I love Linux!         //輸入完成按 Ctrl+D
# ls
anaconda-ks.cfg  test.txt
# cat test.txt
I love Linux!


//SPACE     Display next k lines of text.  Defaults to current screen size.
//RETURN    Display next k lines of text.  Defaults  to  1                     
# more anaconda-ks.cfg


# less anaconda-ks.cfg


//預設10 列
# head /var/log/messages
Feb 17 22:50:34 centos8 kernel: Linux version 4.18.0-147.el8.x86_64 (mockbuild@kbuilder.bsys.centos.org) (gcc version 8.3.1 20190507 (Red Hat 8.3.1-4) (GCC)) #1 SMP Wed Dec 4 21:51:45 UTC 2019


// 指定3列
# tail -3 /var/log/messages
Mar 28 17:00:34 centos8 systemd[1]: Started dnf makecache.
Mar 28 17:04:57 centos8 systemd[1]: Starting Cleanup of Temporary Directories...
Mar 28 17:04:57 centos8 systemd[1]: Started Cleanup of Temporary Directories.


// ----follow 持續監控記錄檔,有新資料馬上顯示    ^C 中斷
# tail -f /var/log/messages


//產生空白檔案
# touch kk1.txt
# ls
anaconda-ks.cfg  kk1.txt


//change file timestamps
# ls -l
-rw-------. 1 root root 1262  2月 17 22:49 anaconda-ks.cfg
# touch anaconda-ks.cfg
# ls -l
-rw-------. 1 root root 1262  3月 29 15:33 anaconda-ks.cfg





-------------------------------------- mkdir, rmdir

// make directories
# mkdir dir1
# ls -l
-rw-------. 1 root root 1262  3月 29 15:33 anaconda-ks.cfg
drwxr-xr-x. 2 root root    6  3月 29 15:36 dir1


// remove empty directories
# touch dir1/file1
# ls dir1/file1
dir1/file1

// -f, --force   -r, -R, --recursive
# rm -r dir1
rm: descend into directory 'dir1'? y
rm:是否移除普通空白檔案'dir1/file1'? y
rm:是否移除目錄'dir1'? y
# ls
anaconda-ks.cfg






-------------------------------------- link

# echo "HelloWorld" > data.txt

// -i, --inode
# ls -li
8851206 -rw-r--r--. 1 root root   11  3月 29 17:21 data.txt

//-s, --symbolic make symbolic links instead of hard links
# ln -s data.txt slink
# ls -li
8851206 -rw-r--r--. 1 root root   11  3月 29 17:21 data.txt
8851201 lrwxrwxrwx. 1 root root    8  3月 29 17:24 slink -> data.txt
// l: link    rwx: link 沒自己權限,視真實檔案為主
//2個 inode 編號不同


# cat slink
HelloWorld


# rm data.txt
rm:是否移除普通檔案'data.txt'? y
# ls -l slink
lrwxrwxrwx. 1 root root 8  3月 29 17:24 slink -> data.txt
// slink 變成紅色警戒,表連結無效
//刪除 真實檔案的檔名
//符號連結 symbolic link 就無法取得真實檔案的 inode 資訊內的 Block 區塊位置

# cat slink
cat: slink: 沒有此一檔案或目錄

# rm slink
rm:是否移除符號連結'slink'? y




# echo "HelloWorld" > data2.txt

// Create hard links by default, symbolic links with --symbolic. 
# ln data2.txt hlink
# ls -li
8851201 -rw-r--r--. 2 root root   11  3月 29 17:38 data2.txt
8851201 -rw-r--r--. 2 root root   11  3月 29 17:38 hlink
//2個 inode 編號相同



# rm data2.txt
rm:是否移除普通檔案'data2.txt'? y

# ls -li
8851201 -rw-r--r--. 1 root root   11  3月 29 17:38 hlink

# cat hlink
HelloWorld

// 硬連結 hard link 複製真實檔案的 inode 資訊,所以刪除 真實檔案的檔名
//硬連結仍可以取得真實檔案的 inode 資訊內的 Block 區塊位置 




symbolic link       可跨越分割區       支援目錄   刪除真實檔案後成無效連結   無法自訂權限
hard         link   不可跨越分割區   不支援目錄   刪除真實檔案後仍有效連結  可以自訂權限






-------------------------------------- 執行檔

//執行檔的絕對路徑
# ls /usr/bin/du
/usr/bin/du
#  /usr/bin/du
44      .


//環境變數 PATH 設定 自動搜尋目錄裡的執行檔
# echo $PATH
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin
# du
44      .



# echo "HelloWorld!" > runMe
# ls -l
-rw-r--r--. 1 root root   12  3月 29 22:16  runMe

# chmod u+x runMe
# ls -l
-rwxr--r--. 1 root root   12  3月 29 22:16  runMe

# runMe
-bash: runMe:命令找不到

//執行目前所在目錄下的執行檔
# ./runMe
./runMe: 列 1: HelloWorld!:命令找不到




-------------------------------------- 硬碟空間使用情形

//report file system disk space usage 各分割區使用情況
//-h, --human-readable
# df -h
檔案系統                     容量  已用  可用 已用% 掛載點
devtmpfs                     886M     0  886M    0% /dev
tmpfs                        904M     0  904M    0% /dev/shm
tmpfs                        904M  8.7M  895M    1% /run
tmpfs                        904M     0  904M    0% /sys/fs/cgroup
/dev/mapper/cl_centos8-root  6.2G  1.4G  4.9G   23% /
/dev/sda1                    976M  136M  774M   15% /boot
tmpfs                        181M     0  181M    0% /run/user/0



//estimate file space usage 目前目錄下( 含子目錄)已用空間
 # du -h
32K     .


 //-s, --summarize
# du -sh /var/
115M    /var/
# du -sh /var/*
0       /var/adm
24M     /var/cache
0       /var/crash
...






-------------------------------------- 重導輸出 redirect ,重導輸入

//若導向到的檔案已經存在,則會被覆蓋
# echo "this is old data" > myfile
# cat myfile
this is old data

//  >> 新增至尾端
# echo "this is new data" >> myfile
# cat myfile
this is old data
this is new data


# ls
anaconda-ks.cfg 
# ls kk1.txt
ls: 無法存取 'kk1.txt': 沒有此一檔案或目錄

// stdin:0   stdout:1   stderr:2
# ls kk1.txt 2> myError

# ls
anaconda-ks.cfg  myError

# cat myError
ls: 無法存取 'kk1.txt': 沒有此一檔案或目錄




# echo "電腦使用筆記" > mydata
# cat mydata
電腦使用筆記

//行數   字數   byte數
# wc < mydata
 1  1 19

# ls -l
-rw-r--r--. 1 root root   19  3月 29 22:58 mydata




-------------------------------------- 迴路介面 loopback interface


//ifconfig 替換為 ip addr
# ip addr show
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
    inet6 ::1/128 scope host
       valid_lft forever preferred_lft forever
2: ens33: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP group default qlen 1000
    link/ether 00:0c:29:67:87:0a brd ff:ff:ff:ff:ff:ff
    inet 192.168.2.103/24 brd 192.168.2.255 scope global noprefixroute ens33
       valid_lft forever preferred_lft forever
    inet6 fe80::738b:2e41:1d4b:20f3/64 scope link noprefixroute
       valid_lft forever preferred_lft forever



# cat /etc/hosts
127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
::1         localhost localhost.localdomain localhost6 localhost6.localdomain6



# ping localhost
PING localhost(localhost (::1)) 56 data bytes
64 bytes from localhost (::1): icmp_seq=1 ttl=64 time=0.069 ms
.
.




-------------------------------------- nmcli 設定IP 相關


# nmcli device status
DEVICE  TYPE      STATE     CONNECTION
ens33   ethernet  已連線    ens33
lo      loopback  不受管理  --



# nmcli connection modify ens33 ipv4.address 192.168.2.103/24

# nmcli connection modify ens33 ipv4.gateway 192.168.2.1

# nmcli connection modify ens33 ipv4.dns 192.168.2.1


# nmcli device connect ens33
裝置「ens33」已成功以「9cb77588-c78e-40b0-acbe-3be164c3e385」啟用。
# nmcli device disconnect ens33


# nmcli connection up ens33
連線已成功啟用(D-Bus 啟用路徑:/org/freedesktop/NetworkManager/ActiveConnection/3)
# nmcli connection down ens33



# nmcli device show ens33
GENERAL.DEVICE:                         ens33
GENERAL.TYPE:                           ethernet
GENERAL.HWADDR:                         00:0C:29:67:87:0A
GENERAL.MTU:                            1500
GENERAL.STATE:                          100 (已連線)
GENERAL.CONNECTION:                     ens33
GENERAL.CON-PATH:                       /org/freedesktop/NetworkManager/ActiveConnectio>
WIRED-PROPERTIES.CARRIER:               開
IP4.ADDRESS[1]:                         192.168.2.103/24
IP4.GATEWAY:                            192.168.2.1
IP4.ROUTE[1]:                           dst = 192.168.2.0/24, nh = 0.0.0.0, mt = 100
IP4.ROUTE[2]:                           dst = 0.0.0.0/0, nh = 192.168.2.1, mt = 100
IP4.DNS[1]:                             192.168.2.1
IP6.ADDRESS[1]:                         fe80::738b:2e41:1d4b:20f3/64
IP6.GATEWAY:                            --
IP6.ROUTE[1]:                           dst = fe80::/64, nh = ::, mt = 100
IP6.ROUTE[2]:                           dst = ff00::/8, nh = ::, mt = 256, table=255




//CLI 下的圖形設計工具
# nmtui edit ens33

# systemctl restart NetworkManager.service






------------------------------ ip 工具  由命令所做的設定,不會存至系統組態檔,所只適合測試用。

# ip addr show
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
.
.
2: ens33: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP group default qlen 1000
link/ether 00:0c:29:67:87:0a brd ff:ff:ff:ff:ff:ff
    inet 192.168.2.103/24 brd 192.168.2.255 scope global noprefixroute ens33
.
.


//顯示特定設備的統計資料
# ip -s link show ens33
2: ens33: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP mode DEFAULT group default qlen 1000
    link/ether 00:0c:29:67:87:0a brd ff:ff:ff:ff:ff:ff
    RX: bytes  packets  errors  dropped overrun mcast
    818966     6508     0       0       0       0
    TX: bytes  packets  errors  dropped carrier collsns
    601940     3995     0       0       0       0



// 指派 ip 位址給設備
# ip addr add 192.168.2.104/24 brd + dev ens33
# ip addr
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
.
.
2: ens33: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP group default qlen 1000
    link/ether 00:0c:29:67:87:0a brd ff:ff:ff:ff:ff:ff
    inet 192.168.2.103/24 brd 192.168.2.255 scope global noprefixroute ens33
       valid_lft forever preferred_lft forever
    inet 192.168.2.104/24 brd 192.168.2.255 scope global secondary ens33
.
.
      
# ping 192.168.2.104
PING 192.168.2.104 (192.168.2.104) 56(84) bytes of data.
64 bytes from 192.168.2.104: icmp_seq=1 ttl=64 time=0.071 ms



若 Host is Wondows7 無法 ping :
 控制台\系統及安全性\Windows 防火牆 --> 進階設定 --> 輸入規則 --> 檔案及印表機共用 (回應要求 - ICMPv4-In) --> 私人,公用 --> 已啟用 --> 是




# ip addr del 192.168.2.104/24 dev ens33
# ip addr
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen  1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
.
.
2: ens33: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP group defa ult qlen 1000
    link/ether 00:0c:29:67:87:0a brd ff:ff:ff:ff:ff:ff
    inet 192.168.2.103/24 brd 192.168.2.255 scope global noprefixroute ens33
.
.

//啟用
# ip link set ens33 up

//停用
# ip link set ens33 down






-------------------------------------- NetworkManager 工具


# systemctl status NetworkManager
● NetworkManager.service - Network Manager
   Loaded: loaded (/usr/lib/systemd/system/NetworkManager.service; enabled; vendor pre>
   Active: active (running) since Mon 2020-02-24 16:12:24 CST; 41min ago


# ls /usr/lib/systemd/system
.
.
NetworkManager.service 




//系統網路組態目錄下的設定檔
# ls /etc/sysconfig/network-scripts/
ifcfg-ens33

# cat /etc/sysconfig/network-scripts/ifcfg-ens33
TYPE=Ethernet
PROXY_METHOD=none
BROWSER_ONLY=no
BOOTPROTO=none                  //是否自動取的IP;若是,dhcp 。若否,static 或 none
DEFROUTE=yes
IPV4_FAILURE_FATAL=no
IPV6INIT=yes
IPV6_AUTOCONF=yes
IPV6_DEFROUTE=yes
IPV6_FAILURE_FATAL=no
IPV6_ADDR_GEN_MODE=stable-privacy
NAME=ens33
UUID=9cb77588-c78e-40b0-acbe-3be164c3e385
DEVICE=ens33
ONBOOT=yes                          //開機是否啟用此網路卡
IPADDR=192.168.2.103
PREFIX=24
GATEWAY=192.168.2.1
DNS1=192.168.2.1
IPV6_PRIVACY=no


# systemctl restart NetworkManager.service






-------------------------------------- 網路測試工具


//hostnamectl 取替 hostname
# hostnamectl set-hostname CentOS8.Ku
# hostnamectl
   Static hostname: CentOS8.Ku
         Icon name: computer-vm
           Chassis: vm
        Machine ID: 964572b3e4d64c338b0bc8c066ac099c
           Boot ID: 1c016fbe42b8401d84e934a75a3a450e
    Virtualization: vmware
  Operating System: CentOS Linux 8 (Core)
       CPE OS Name: cpe:/o:centos:centos:8
            Kernel: Linux 4.18.0-147.5.1.el8_1.x86_64
      Architecture: x86-64




//測試主機回應 Hinet 的 DNS
# ping 168.95.1.1
PING 168.95.1.1 (168.95.1.1) 56(84) bytes of data.
64 bytes from 168.95.1.1: icmp_seq=1 ttl=247 time=9.10 ms
.



 //ss  is  used  to  dump socket statistics.
//ss 取替 netstat
t:tcp協定   u:udp協定   n:不用名稱以port顯示   p:連線由哪個行程處理   l:在傾聽的連線

# ss -tunpl
Netid   State     Recv-Q    Send-Q        Local Address:Port       Peer Address:Port 
udp     UNCONN    0         0             127.0.0.53%lo:53              0.0.0.0:*        users:(("systemd-resolve",pid=1693,fd=18))


//檢視tcp連線
# ss -t
State    Recv-Q     Send-Q          Local Address:Port           Peer Address:Port
ESTAB    0          52              192.168.2.103:ssh           192.168.2.100:54723


//檢視udp
# ss -u
Recv-Q      Send-Q              Local Address:Port              Peer Address:Port




//tracepath 取替  traceroute/traceroute6
# tracepath 8.8.8.8
 1?: [LOCALHOST]                      pmtu 1500
 1:  _gateway                                              1.110ms
 1:  _gateway                                              1.143ms
 2:  ZyXEL.Home                                            1.737ms
.
.


//ip route 取替  route
# ip route show | column -t
default               via  192.168.2.1  dev     ens33   proto  static  metric  100         
192.168.2.0/24  dev  ens33           proto  kernel  scope  link    src       192.168.2.103 


# ip route show | column -t > kkRouteTable.txt
# cat kkRouteTable.txt
default               via  192.168.2.1  dev     ens33    proto  static  metric  100         
192.168.2.0/24  dev  ens33           proto  kernel   scope  link    src     192.168.2.103  metric  100



# ip -6 route show | column -t
::1        dev  lo     proto  kernel  metric  256  pref  medium
fe80::/64  dev  ens33  proto  kernel  metric  100  pref  medium





# ip route show
default via 192.168.1.1 dev ens32 proto static metric 100
192.168.1.0/24 dev ens32 proto kernel scope link src 192.168.1.4 metric 100

# ip addr add 10.15.150.1/24 brd + dev ens32
# ip addr show
...

2: ens32: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP group default qlen 1000
    link/ether 00:0c:29:2f:19:6f brd ff:ff:ff:ff:ff:ff
    inet 192.168.1.4/24 brd 192.168.1.255 scope global noprefixroute ens32
       valid_lft forever preferred_lft forever
    inet 10.15.150.1/24 brd 10.15.150.255 scope global ens32
       valid_lft forever preferred_lft forever
...


# ip route add 10.15.150.0/24 192.168.1.1 dev ens32         //增加靜態路由 
# ip route show
default via 192.168.1.1 dev ens32 proto static metric 100
10.15.150.0/24 dev ens32 proto kernel scope link src 10.15.150.1
192.168.1.0/24 dev ens32 proto kernel scope link src 192.168.1.4 metric 100

# ping 10.15.150.1
PING 10.15.150.1 (10.15.150.1) 56(84) bytes of data.
64 bytes from 10.15.150.1: icmp_seq=1 ttl=64 time=0.064 ms
...


# ip route del 10.15.150.0/24
# ip route show
default via 192.168.1.1 dev ens32 proto static metric 100
192.168.1.0/24 dev ens32 proto kernel scope link src 192.168.1.4 metric 100

# ip addr del 10.15.150.1/24 dev ens32
# ip addr show
...

2: ens32: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP group default qlen 1000
    link/ether 00:0c:29:2f:19:6f brd ff:ff:ff:ff:ff:ff
    inet 192.168.1.4/24 brd 192.168.1.255 scope global noprefixroute ens32
       valid_lft forever preferred_lft forever
...







//ARP Address Resolution Protocol 位址解析協定,由已知的 IP 位址查問其相對應的網路實體位址MAC
 RARP Reverse Address Resolution Protocol 反向位址解析協定,由已知的網路實體位址(MAC 位址)查詢其相對應的 IP 位址

//ip neighbor 取替  arp
# ip neighbor show
192.168.2.1 dev ens33 lladdr 80:1f:02:1f:33:86 STALE
192.168.2.100 dev ens33 lladdr 54:04:a6:6b:67:7d REACHABLE





被淘汰的工具只是不在預設安裝所包含的,所以是可以利用 yum 把他安裝回來
Note:在 yum 中不知道套件的名稱,可以用 provides 和 list 直接搜尋 package 裡面的工具

//DNF  is the next upcoming major version of YUM
# dnf provides */ifconfig
net-tools-2.0-0.51.20160912git.el8.x86_64 : Basic networking tools
軟體庫  :BaseOS
符合來源:
檔案名稱:/usr/sbin/ifconfig


# dnf -y install net-tools


# netstat -r | column -t
Kernel       IP        routing        table
Destination  Gateway   Genmask        Flags  MSS  Window  irtt  Iface
default      _gateway  0.0.0.0        UG     0    0       0     ens33
192.168.2.0  0.0.0.0   255.255.255.0  U      0    0       0     ens33




# dnf -y install bind-utils

# dig 168.95.1.1


# dnf -y install traceroute
# traceroute www.chehjh.kh.edu.tw





----------------------------------------------------------------- Firewalld


//查詢啟用狀態
# firewall-cmd --state
running


# firewall-cmd --get-zones
block dmz drop external home internal public trusted work

# ls /usr/lib/firewalld/zones/
block.xml  drop.xml      home.xml      public.xml   work.xml
dmz.xml    external.xml  internal.xml  trusted.xml



# firewall-cmd --get-active-zone
public
  interfaces: ens32



 //了解目前zone的詳細設定
# firewall-cmd --zone=public --list-all
public (active)
  target: default
  icmp-block-inversion: no
  interfaces: ens32
  sources:
  services: cockpit dhcpv6-client ssh
...



// 名稱 vsfpt 、vsftpd 都不是
# firewall-cmd --get-service | grep ftp         
...
cockpit condor-collector ctdb dhcp dhcpv6 dhcpv6-client distcc dns dns-over-tls docker-registry
...
freeipa-ldaps freeipa-replication freeipa-trust ftp ganglia-client ganglia-master git grafana gre high-availability http https imap imaps ipp ipp-client ipsec irc ircs iscsi-target isns jenkins kadmin
...
network llmnr managesieve matrix mdns memcache minidlna mongodb mosh mountd mqtt mqtt-tls ms-wbt mssql murmur mysql nfs nfs3 nmea-0183 nrpe ntp nut openvpn ovirt-imageio ovirt-
...
rpc-bind rsh rsyncd rtsp salt-master samba samba-client samba-dc sane sip sips slp smtp smtp-submission smtps snmp snmptrap spideroak-lansync spotify-sync squid ssdp ssh steam-streaming svdrp svn syncthing syncthing-gui synergy syslog syslog-tls telnet tentacle tft  tftp-client tile38 tinc
...


# ls /usr/lib/firewalld/services/ | grep ftp
ftp.xml
tftp-client.xml
tftp.xml



//將服務加入規則
# firewall-cmd --zone=public --add-service=ftp
success

# firewall-cmd --zone=public --list-all
public (active)
...
  services: cockpit dhcpv6-client ftp ssh
  ports:
  ...


//將埠口加入規則
# firewall-cmd --zone=public --add-port=8080/tcp
success
# firewall-cmd --zone=public --list-all
public (active)
...
  services: cockpit dhcpv6-client ftp ssh
  ports: 8080/tcp
  ...




//將服務與埠口移除
# firewall-cmd --zone=public --remove-port=8080/tcp
success
# firewall-cmd --zone=public --list-all
public (active)
 ...
  services: cockpit dhcpv6-client ftp ssh
  ports:


# firewall-cmd --zone=public --remove-service=ftp
success
# firewall-cmd --zone=public --list-all
public (active)
 ...
  services: cockpit dhcpv6-client ssh
  ports:





// firewalld.service 開機是否啟動
# systemctl disable firewalld.service
# systemctl enable firewalld.service
# systemctl is-enabled firewalld.service
enabled


# ls /usr/lib/systemd/system
...
crond.service                           selinux-autorelabel-mark.service
...
default.target.wants                    sshd.service
..
dnf-makecache.service                   sssd-kcm.service
...
firewalld.service                       suspend-then-hibernate.target
...
NetworkManager.service                  systemd-rfkill.socket
...



//停止FirewallD服務
# systemctl stop firewalld.service
# systemctl start firewalld.service
# systemctl is-active firewalld.service
active



# systemctl status firewalld.service
● firewalld.service - firewalld - dynamic firewall daemon
   Loaded: loaded (/usr/lib/systemd/system/firewalld.service; enabled; vendor preset: enabled)
   Active: active (running) since Thu 2020-03-05 10:58:39 CST; 1min 51s ago

2020年2月23日 星期日

CentOS8 vsftp


參考來源:
https://www.server-world.info/en/note?os=CentOS_8&p=ftp&f=1



--------------------------------------------------- 安裝、設定
# dnf -y install vsftpd

# vi /etc/vsftpd/vsftpd.conf
...
anonymous_enable=NO
...
chroot_local_user=YES

allow_writeable_chroot=YES
...
# add to the end
# fix PASV ports to allow FTP access with PASV
pasv_enable=YES





--------------------------------------------------- 套件安裝目錄與檔案

//執行檔
# ls /usr/sbin | grep vsftpd
vsftpd


//設定檔
# ls /etc/vsftpd
ftpusers  user_list  vsftpd.conf


//FTP 站台 根目錄
# ls /var/ftp
pub






--------------------------------------------------- 啟動 服務

// systemctl 指令,可列出目前所有服務的狀態資訊
# systemctl | grep vsftpd
vsftpd.service 

# systemctl start vsftpd
# systemctl enable vsftpd
# systemctl status vsftpd





--------------------------------------------------- 檢查套件資訊、服務名稱、行程 or 執行檔所在位置

# rpm -qa | grep vsftpd
vsftpd-3.0.3-28.el8.x86_64


# ps -aux | grep vsftp
root       2618  0.0  0.0  26980   408 ?        Ss   14:30   0:00 /usr/sbin/vsftpd   /etc vsftpd/vsftpd.conf

# ls /usr/sbin | grep vsftp
vsftpd

# ls /usr/lib/systemd/system | grep vsftp
vsftpd.service
vsftpd@.service
vsftpd.target



--------------------------------------------------- 開啟 防火牆

# firewall-cmd --state
running

# firewall-cmd --get-zones
block dmz drop external home internal public trusted work

# firewall-cmd --get-active-zone
public
  interfaces: ens33

# firewall-cmd --zone=public --list-all
public (active)
  target: default
  icmp-block-inversion: no
  interfaces: ens33
  sources:
  services: cockpit dhcpv6-client http https ssh
...


//列出 firewall-cmd 所有可用的服務
# firewall-cmd --get-service | grep ftp         //vsfpt 、vsftpd 都找不到

//這些服務定義在此資料夾內
# ls /usr/lib/firewalld/services/ | grep ftp
ftp.xml
tftp-client.xml
tftp.xml


# firewall-cmd --permanent --zone=public --add-service=ftp
success

# firewall-cmd --reload
success

# firewall-cmd --zone=public --list-all
public (active)
  target: default
  icmp-block-inversion: no
  interfaces: ens33
  sources:
  services: cockpit dhcpv6-client ftp http https ssh


--------------------------------------------------- SELinux

# getsebool -a | grep ftp*

# setsebool -P ftpd_full_access on
# setsebool -P tftp_home_dir on






--------------------------------------------------- 新增 群組、使用者

//建立群組
# groupadd Gftp
# cat /etc/group
.
.
Gftp:x:1004:


//建立帳號並指定已存在的的群組
# useradd -g Gftp s306
# passwd s306
更改使用者 s306 的密碼。
新 密碼:


//帳號資料
# cat /etc/passwd
.
.
s306:x:1003:1004::/home/s306:/bin/bash


//密碼資料
# cat /etc/shadow
.
.
s306:$6$1pUNBa5VJIUydee8$zNtG40zl2wBuxjhtF/aAWrxeI3s1bVRGexWlCVFzmpCk9MZW5              ajUFEtIL19A518.v8CPLUV8n/Kj6RUE3dCG//:18315:0:99999:7:::


//家目錄
# ls -l /home
.
.
drwx------. 2 s306  Gftp  62  2月 23 22:27 s306


//使用者相關資訊
# id s306
uid=1003(s306) gid=1004(Gftp) groups=1004(Gftp)



//刪除帳號、家目錄及沒有含其它帳號的群組
# userdel -r 帳號





--------------------------------------------------- 上課用 班級資料夾

# su -l s306
$ mkdir {01..40}
$ ls
01  04  07  10  13  16  19  22  25  28  31  34  37  40
02  05  08  11  14  17  20  23  26  29  32  35  38
03  06  09  12  15  18  21  24  27  30  33  36  39


$ su
密碼:
# cd
#


# chattr +a -R /home/s306        //+a只能以附加方式寫入

# lsattr /home
-----a------------- /home/s306


ftp://192.168.2.103/座號/
使用者名稱:s306
密碼            :123456


# ls /home/s306/*/1.docx





--------------------------------------------------- 檔案總管 上傳 中文檔名 呈現亂碼

改用 FileZilla_3.46.3_win64_sponsored-setup.exe
站台管理員 --> 新站台 --> 字元集 --> 強制使用 UTF-8






--------------------------------------------------- 移除套件

# dnf -y remove vsftpd






2020年2月20日 星期四

CentOS8 安裝及基本設定 與 安裝 Apache, MariaDB, PHP






------------------------------------------------------------------- CentOS8 安裝及基本設定

VMware-player-15.5.1-15018445.exe
CentOS-8.1.1911-x86_64-dvd1.iso

setup!




# uname -r
4.18.0-147.el8.x86_64        //核心版本:4.18.0   已經修改 147次  x86相容電腦i686  64位元


# w      //列出目前登入使用者資訊
 23:10:19 up 1 min,  1 user,  load average: 0.18, 0.10, 0.04
USER     TTY      FROM             LOGIN@   IDLE   JCPU   PCPU WHAT
root        pts/0      192.168.2.100    23:09       1.00s     0.04s   0.01s   w


# date
一  2月 17 23:16:37 CST 2020


# echo $LANG
zh_TW.UTF-8


# locale
LANG=zh_TW.UTF-8
LC_CTYPE="zh_TW.UTF-8"
LC_NUMERIC="zh_TW.UTF-8"
LC_TIME="zh_TW.UTF-8"
LC_COLLATE="zh_TW.UTF-8"
LC_MONETARY="zh_TW.UTF-8"
LC_MESSAGES="zh_TW.UTF-8"
LC_PAPER="zh_TW.UTF-8"
LC_NAME="zh_TW.UTF-8"
LC_ADDRESS="zh_TW.UTF-8"
LC_TELEPHONE="zh_TW.UTF-8"
LC_MEASUREMENT="zh_TW.UTF-8"
LC_IDENTIFICATION="zh_TW.UTF-8"
LC_ALL=


# ip addr show
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
    inet6 ::1/128 scope host
       valid_lft forever preferred_lft forever
2: ens33: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP group default qlen 1000
    link/ether 00:0c:29:67:87:0a brd ff:ff:ff:ff:ff:ff
    inet 192.168.2.103/24 brd 192.168.2.255 scope global noprefixroute ens33
       valid_lft forever preferred_lft forever
    inet6 fe80::738b:2e41:1d4b:20f3/64 scope link noprefixroute
       valid_lft forever preferred_lft forever


# nmtui
Network Manager:
編輯連線
啟用連線
設定系統主機名稱



# vi /etc/sysconfig/network-scripts/ifcfg-ens33
TYPE="Ethernet"
PROXY_METHOD="none"
BROWSER_ONLY="no"
BOOTPROTO="none"
DEFROUTE="yes"
IPV4_FAILURE_FATAL="no"
IPV6INIT="yes"
IPV6_AUTOCONF="yes"
IPV6_DEFROUTE="yes"
IPV6_FAILURE_FATAL="no"
IPV6_ADDR_GEN_MODE="stable-privacy"
NAME="ens33"
UUID="9cb77588-c78e-40b0-acbe-3be164c3e385"
DEVICE="ens33"
ONBOOT="yes"
IPADDR="192.168.2.103"
PREFIX="24"
GATEWAY="192.168.2.1"
DNS1="192.168.2.1"
IPV6_PRIVACY="no"


# systemctl restart NetworkManager.service




# yum -y update




---------------------------------------------- hostnamectl

//hostnamectl 取替 hostname
# hostnamectl set-hostname CentOS8.Ku
# hostnamectl
   Static hostname: CentOS8.Ku
         Icon name: computer-vm
           Chassis: vm
        Machine ID: 964572b3e4d64c338b0bc8c066ac099c
           Boot ID: 1c016fbe42b8401d84e934a75a3a450e
    Virtualization: vmware
  Operating System: CentOS Linux 8 (Core)
       CPE OS Name: cpe:/o:centos:centos:8
            Kernel: Linux 4.18.0-147.5.1.el8_1.x86_64
      Architecture: x86-64




# vi /etc/hostname
Ku.CentOS8








------------------------------------------------------------------- Linux安裝 Apache, MariaDB, PHP (LAMP)

# yum -y install httpd httpd-tools
# systemctl start httpd
# systemctl enable httpd
Created symlink /etc/systemd/system/multi-user.target.wants/httpd.service → /usr/lib/systemd/system/httpd.service.




# firewall-cmd --permanent --zone=public --add-service=http    //80 port
success
# firewall-cmd --permanent --zone=public --add-service=https    //443 port
success
# firewall-cmd --reload
success
# systemctl reload firewalld




http://192.168.2.103/




# yum -y install mariadb-server mariadb
# systemctl start mariadb
# systemctl enable mariadb
Created symlink /etc/systemd/system/mysql.service → /usr/lib/systemd/system/mari        adb.service.
Created symlink /etc/systemd/system/mysqld.service → /usr/lib/systemd/system/mar        iadb.service.
Created symlink /etc/systemd/system/multi-user.target.wants/mariadb.service → /u        sr/lib/systemd/system/mariadb.service.

# mysql_secure_installation

Enter current password for root (enter for none):
OK, successfully used password, moving on...

//設定 root 帳號密碼
Set root password? [Y/n] y
New password:                                 //db123456
Re-enter new password:
Password updated successfully!

//是否移除匿名帳號
Remove anonymous users? [Y/n] y

//是否允許 root 帳號遠端登入
Disallow root login remotely? [Y/n] y

//是否移除 test 資料庫
Remove test database and access to it? [Y/n] n

//
Reload privilege tables now? [Y/n] y


# mysql -u root -p
Enter password:        //db123456


MariaDB [(none)]> show variables like 'version';        //MariaDB 版本
+---------------+-----------------+
| Variable_name | Value           |
+---------------+-----------------+
| version       | 10.3.17-MariaDB |
+---------------+-----------------+


MariaDB [(none)]> 
Ctrl-C -- exit!
Aborted




#  yum -y install php php-fpm php-mysqlnd php-opcache php-gd php-ldap php-odbc php-pear php-xml php-xmlrpc php-mbstring php-snmp php-soap curl curl-devel


//CentOS 8 的 Apache, 預設使用 PHP-FPM 執行 PHP, 所以需要啟動 PHP-FPM

# systemctl start php-fpm
# systemctl enable php-fpm
Created symlink /etc/systemd/system/multi-user.target.wants/php-fpm.service → /usr/lib/systemd/system/php-fpm.service.

# systemctl restart httpd





//讓 SELinux 允許 Apache 透過 PHP-FPM 執行 PHP 程式碼:
# setsebool -P httpd_execmem 1




# vi /var/www/html/info.php
<?php
phpinfo();
?>


http://192.168.2.103/info.php







------------------------------------------------------------------- MariaDB
參考資料:
佳魁資訊--更純正開放 MySQL MariaDB 的完全制霸手冊--黃縉華

# mysql -u root -p
Enter password:        //db123456



/************ 建立資料庫 表 與刪除 ******************

MariaDB [(none)]> create database dbTest;
MariaDB [(none)]> show databases;





資料庫儲存引擎:
決定 MariaDB 資料庫中的表,可以使用的儲存方式、交易處理方式...等

方法1:
MariaDB [(none)]> show engines\G;       // \G 結果顯示較美觀
.
.
*************************** 10. row ***************************
      Engine: InnoDB
     Support: DEFAULT        // MariaDB 是否支援 。預設
     Comment: Supports transactions, row-level locking, foreign keys and encryption for tables    //評論
Transactions: YES        //是否支援交易處理
          XA: YES           //是否分散式交易處理的 XA 標準
  Savepoints: YES       //否支援儲存點,以便交易復原到儲存點




方法2:
MariaDB [(none)]> show variables like 'storage_engine';        //查詢預設儲存引擎
+----------------+--------+
| Variable_name  | Value  |
+----------------+--------+
| storage_engine | InnoDB |
+----------------+--------+




MariaDB [dbKu]> show variables like 'character_set%';        //查詢字元集
+--------------------------+------------------------------+
| Variable_name            | Value                        |
+--------------------------+------------------------------+
| character_set_database   | latin1                 



???修改
default storage engine  and  character_set
???



MariaDB [dbTest]> show create database dbTest\G;
*************************** 1. row ***************************
       Database: dbTest
Create Database: CREATE DATABASE `dbTest` /*!40100 DEFAULT CHARACTER SET latin1 */



MariaDB [(none)]> use dbTest;
MariaDB [dbTest]> create table tblStu(sid int primary key auto_increment,na varchar(10));
MariaDB [dbTest]> show tables;

MariaDB [dbTest]> show create table tblStu\G;
*************************** 1. row ***************************
       Table: tblStu
Create Table: CREATE TABLE `tblStu` (
  `sid` int(11) NOT NULL AUTO_INCREMENT,
  `na` varchar(10) DEFAULT NULL,
  PRIMARY KEY (`sid`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1


MariaDB [dbTest]> drop table tblStu;
MariaDB [dbTest]> show tables;


MariaDB [dbTest]> drop database dbTest;
MariaDB [(none)]> show databases;

# ls /var/lib/mysql/            //MariaDB 安裝資料夾沒有 dbTest 資料夾











/************ 建立 資料庫 並設 character set ************

|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||

MariaDB [(none)]> create database dbKu character set='utf8' collate='utf8_unicode_ci';
MariaDB [(none)]> show databases;

|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||

//建立 database 即 設定 character set='utf8' collate='utf8_unicode_ci
//新增 表 才能輸入中文 或匯入 表 時中文才不會呈現亂碼


MariaDB [dbKu]> show engines\G;
.
.
*************************** 10. row ***************************
      Engine: InnoDB
     Support: DEFAULT
     Comment: Supports transactions, row-level locking, foreign keys and encryption for tables
Transactions: YES
          XA: YES
  Savepoints: YES
.
.



MariaDB [dbKu]> show variables like 'storage%';
+----------------+--------+
| Variable_name  | Value  |
+----------------+--------+
| storage_engine | InnoDB |
+----------------+--------+
1 row in set (0.001 sec)



MariaDB [dbKu]> show variables like 'character%';
+--------------------------+------------------------------+
| Variable_name            | Value                        |
+--------------------------+------------------------------+
| character_set_client     | utf8                         |
| character_set_connection | utf8                         |
| character_set_database   | utf8                         |
.
.


MariaDB [dbKu]> show create database dbKu\G;
*************************** 1. row ***************************
       Database: dbKu
Create Database: CREATE DATABASE `dbKu` /*!40100 DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci */






/****************** 建立 表 ************
MariaDB [dbKu]> create table tblStu (sid int primary key  auto_increment, gra varchar(1), cla varchar(2), sno varchar(2), na varchar(10),  pwd varchar(10));
MariaDB [dbKu]> show tables;

# ls /var/lib/mysql/dbKu/            // MariaDB 安裝資料夾
db.opt  tblStu.frm  tblStu.ibd


MariaDB [dbKu]> describe tblStu;
+-------+-------------+------+-----+---------+----------------+
| Field | Type        | Null | Key | Default | Extra          |
+-------+-------------+------+-----+---------+----------------+
| sid   | int(11)     | NO   | PRI | NULL    | auto_increment |
| gra   | varchar(1)  | YES  |     | NULL    |                |
| cla   | varchar(2)  | YES  |     | NULL    |                |
| sno   | varchar(2)  | YES  |     | NULL    |                |
| na    | varchar(10) | YES  |     | NULL    |                |
| pwd   | varchar(10) | YES  |     | NULL    |                |
+-------+-------------+------+-----+---------+----------------+



MariaDB [dbKu]> show create table tblStu\G;
*************************** 1. row ***************************
       Table: tblStu
Create Table: CREATE TABLE `tblStu` (
  `sid` int(11) NOT NULL AUTO_INCREMENT,
  `gra` varchar(1) COLLATE utf8_unicode_ci DEFAULT NULL,
  `cla` varchar(2) COLLATE utf8_unicode_ci DEFAULT NULL,
  `sno` varchar(2) COLLATE utf8_unicode_ci DEFAULT NULL,
  `na` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL,
  `pwd` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`sid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci







/****************** 表 資料編輯****************** 

MariaDB [dbKu]>  insert into tblStu(gra,cla,sno,na,pwd)values('1','12','40','李大明','123456');
MariaDB [dbKu]> select * from tblStu;


MariaDB [dbKu]> update tblStu set pwd='2222222222' where sid=2;
MariaDB [dbKu]> select * from tblStu;


MariaDB [dbKu]> delete from tblStu where sid=2;
MariaDB [dbKu]> select * from tblStu;







/****************** 備份與還原****************** 

|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||

#mysqldump -u username -p db [tbl1 tbl2 ...] > BK.sql
#ls /var/lib/mysql/dbKu/
#mysql -u username -p db < BK.sql

|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||


1.備份還原 資料表 /////////////////////
# mysqldump -u root -p dbKu tblStu > dbKu_tblStu_BK.sql;
Enter password:        //db123456
# ls                            //root 身分執行
dbKu_tblStu_BK.sql

# cat dbKu_tblStu_BK.sql        //看備份內容

MariaDB [dbKu]> drop table tblStu;
MariaDB [dbKu]> show tables;

# ls /var/lib/mysql/dbKu/         //MariaDB 安裝資料夾內已沒有 tblStu 資料
db.opt

# mysql -u root -p dbKu < dbKu_tblStu_BK.sql;
Enter password:

MariaDB [(none)]> use dbKu;
MariaDB [dbKu]> show tables;
MariaDB [dbKu]> show create table tblStu\G;        //確認 character set




2.備份還原 資料庫 /////////////////////

# mysqldump -u root -p dbKu > dbKu_BK.sql
Enter password:
ls
anaconda-ks.cfg  dbKu_BK.sql  dbKu_tblStu_BK.sql


###### 移除資料庫 再重建立一新資料庫(也可以與原來資料庫不同名),再還原

MariaDB [(none)]> drop database dbKu;
MariaDB [(none)]> show databases;
# ls /var/lib/mysql/


MariaDB [(none)]> create database dbKu character set='utf8' collate='utf8_unicode_ci';
MariaDB [(none)]> show databases;

MariaDB [(none)]> show create database dbKu\G;


# mysql -u root -p dbKu < dbKu_BK.sql
Enter password:


MariaDB [(none)]> use dbKu;
MariaDB [dbKu]> show tables;
MariaDB [dbKu]> select * from tblStu;

MariaDB [dbKu]> show create table tblStu\G;






/****************** 表 匯出與匯入****************** 

匯出  |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||

方法1: MariaDB 內
select fieldNa from TableNa [where ...] into outfile 'outNa.txt' [option];
option:
fields terminated by '字串'             //設定欄位分隔符號,預設 '\t'

MariaDB [dbKu]> select * from tblStu into outfile './tblStu.txt';        // ./ 表 MariaDB 安裝目錄
# ls /var/lib/mysql
tblStu.txt


MariaDB [dbKu]> select * from tblStu into outfile 'tblStu.txt';        //沒寫 自己的 db 資料夾內
# ls /var/lib/mysql/dbKu
db.opt  tblStu.frm  tblStu.ibd  tblStu.txt




方法2:
#mysqldump -u root -p -T db table --目標目錄 [option]

# mysqldump -u root -p -t dbKu tblStu --tab=./
Enter password:
mysqldump: Got error: 1: "Can't create/write to file '/root/tblStu.txt' (Errcode: 13 "Permission denied")" when executing 'SELECT INTO OUTFILE'
???????


# mysqldump -u root -p -t dbKu tblStu --tab=/var/lib/mysql/dbKu;
Enter password:
# ls /var/lib/mysql/dbKu/
db.opt  tblStu.frm  tblStu.ibd  tblStu.sql  tblStu.txt
]# cat /var/lib/mysql/dbKu/tblStu.txt
1       1       12      40      李大明  123456
8       2       13      35      趙無級  2222222
9       3       16      22      王小咪  33333333
11      1       12      40      李大明  123456
12      1       12      37      馬久久  66666



方法3:
mysql -u root -p -e "select ..." dbNa > ./bkNa.txt

# mysql -u root -p -e "select * from tblStu" dbKu > ./stu.txt
Enter password:
# ls
anaconda-ks.cfg  dbKu_BK.sql  dbKu_tblStu_BK.sql  stu.txt
# cat stu.txt
sid     gra     cla     sno     na      pwd
1       1       12      40      李大明  123456
8       2       13      35      趙無級  2222222
9       3       16      22      王小咪  33333333
11      1       12      40      李大明  123456
12      1       12      37      馬久久  66666




匯入  ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||

方法1: MariaDB 內
load data [local] infile file into tblNa [option]
local:本機電腦中文字檔
option:fields terminated by '字串'         // 設定欄位分隔符號,預設 '\t'


# vi /var/lib/mysql/dbKu/tblStu.txt
21      1       12      40      陳名曲  123456
22      2       13      35      蔡不通  2222222

MariaDB [dbKu]> load data infile 'tblStu.txt' into table tblStu;
MariaDB [dbKu]> select * from tblStu;




方法2:
mysqlimport -u root -p [--local] dbNa file [option]
local:本機電腦中文字檔
file:文字檔的路徑和名稱
option:--field-terminated-by=字串        // 設定欄位分隔符號,預設 '\t'


# vi /var/lib/mysql/dbKu/tblStu.txt
33      1       12      40      韓有說  123456

# mysqlimport -u root -p dbKu 'tblStu.txt'
Enter password:
MariaDB [(none)]> use dbKu;
MariaDB [dbKu]> select * from tblStu;



|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||





MariaDB [dbKu]> select * from tblStu into outfile 'tblStu.txt';

# ls /var/lib/mysql/dbKu/
db.opt  tblStu.frm  tblStu.ibd  tblStu.txt


//新增資料再匯入
# vi /var/lib/mysql/dbKu/tblStu.txt
11      1       12      40      李大明  123456
8       2       13      35      趙無級  2222222
9       3       16      22      王小咪  33333333



MariaDB [(none)]> use dbKu;
MariaDB [dbKu]> load data infile 'tblStu.txt' into table tblStu;
MariaDB [dbKu]> select * from tblStu;

MariaDB [dbKu]> insert into tblStu(gra,cla,sno,na,pwd)values('1','12','37','馬久久','66666');
MariaDB [dbKu]> select * from tblStu;
+-----+------+------+------+-----------+----------+
| sid | gra  | cla  | sno  | na        | pwd      |
+-----+------+------+------+-----------+----------+
|   1 | 1    | 12   | 40   | 李大明    | 123456   |
|   8 | 2    | 13   | 35   | 趙無級    | 2222222  |
|   9 | 3    | 16   | 22   | 王小咪    | 33333333 |
11 | 1    | 12   | 40   | 李大明    | 123456   |
|  12 | 1    | 12   | 37   | 馬久久    | 66666    |
+-----+------+------+------+-----------+----------+








/****************** 資料表 相關操作 ****************** 

MariaDB [dbKK]> create table tblStu(sid int primary key auto_increment,na varchar(10) not null);
MariaDB [dbKK]> show tables;


/****** 檢視 表 結構

方法1:
MariaDB [dbKK]> describe tblStu\G;

方法2:較完整
MariaDB [dbKK]> show create table tblStu\G;


/****** 改 表 名 :                        舊 rename 新
MariaDB [dbKK]> alter table tblStu rename tblUser;


/****** 新增欄位
MariaDB [dbKK]> alter table tblUser add phone varchar(10);

MariaDB [dbKK]> describe tblUser;


/******  modify 只能修改欄位 資料類型
MariaDB [dbKK]> alter table tblUser modify na varchar(20);
MariaDB [dbKK]> describe tblUser;


/****** change 可以 同時 修改 欄位名 及 資料類型,或只修改其中一項
MariaDB [dbKK]> alter table tblUser change na name varchar(15);
MariaDB [dbKK]> describe tblUser;


/****** 欄位移到第1個位置
MariaDB [dbKK]> alter table tblUser modify UserNa varchar(20) first;
MariaDB [dbKK]> show create table tblUser\G;


/****** 欄位移到指定位置之後
MariaDB [dbKK]> alter table tblUser modify UserNa varchar(20) after sid;
MariaDB [dbKK]> show create table tblUser\G;


/****** 刪除欄位
MariaDB [dbKK]> alter table tblUser drop phone;
MariaDB [dbKK]> show create table tblUser\G;


/****** 修改 表 的儲存引擎
MariaDB [dbKK]> alter table tblUser engine=MyISAM;
MariaDB [dbKK]> show create table tblUser\G;












          

-------------------------------------------------------------------






-------------------------------------------------------------------







-------------------------------------------------------------------






------------------------------------------------------------------- 

2020年1月28日 星期二

CH13 演算法(全)


Python      序列 List
其他語言 陣列 Array

巴斯卡三角形:
1. 使用二維陣列
2. 使用 2 個一維陣列
3. 使用 1 個一維陣列
4. 使用公式
5. 使用遞迴

------------- 巴斯卡三角形 二維序列

p=[[0]*30 for i in range(20)]
n=10
p[0][1]=1
for i in range(1,(n+1)+1):
    for j in range(1,(n+1)+1):
        p[i][j]=p[i-1][j]+p[i-1][j-1]

for i in range(0,n+1):
    for j in range(0,(i+1)+1):
        print("%4d" %(p[i][j]),end='');
    print()

   0   1
   0   1   1
   0   1   2   1
   0   1   3   3   1
   0   1   4   6   4   1
   0   1   5  10  10   5   1
   0   1   6  15  20  15   6   1
   0   1   7  21  35  35  21   7   1
   0   1   8  28  56  70  56  28   8   1
   0   1   9  36  84 126 126  84  36   9   1
   0   1  10  45 120 210 252 210 120  45  10   1




------------- 巴斯卡三角形 2 個一維序列

list01=[];list02=[]
for i in range(15):
    list01.append(0)
    list02.append(0)

list01[1]=1
print(list01[1:2])
c=0

while c<10:
    for i in range(15):
        list02[i]=list01[i-1]+list01[i]

    for i in range(15):
        list01[i]=list02[i]

    c=c+1
    print(list02[1:c+2])

[1]
[1, 1]
[1, 2, 1]
[1, 3, 3, 1]
[1, 4, 6, 4, 1]
[1, 5, 10, 10, 5, 1]
[1, 6, 15, 20, 15, 6, 1]
[1, 7, 21, 35, 35, 21, 7, 1]
[1, 8, 28, 56, 70, 56, 28, 8, 1]
[1, 9, 36, 84, 126, 126, 84, 36, 9, 1]
[1, 10, 45, 120, 210, 252, 210, 120, 45, 10, 1]




------------- 巴斯卡三角形  2個二維序列

def pascal(n):
    if n<=0:
        return
    else:
        row=[1]
        for i in range(n):
            print(row)
            p=row[:]
            for j in range(1,len(row)):
                row[j]=p[j]+p[j-1]
            row.append(1)

pascal(10) 

[1]
[1, 1]
[1, 2, 1]
[1, 3, 3, 1]
[1, 4, 6, 4, 1]
[1, 5, 10, 10, 5, 1]
[1, 6, 15, 20, 15, 6, 1]
[1, 7, 21, 35, 35, 21, 7, 1]
[1, 8, 28, 56, 70, 56, 28, 8, 1]
[1, 9, 36, 84, 126, 126, 84, 36, 9, 1]




------------- 巴斯卡三角形  一維

n=int(input("幾層:"))
plist=[]
for i in range(1,n+1):
    plist.append(1)
    for j in range(i-2,0,-1):
        #print(i,j,plist[j],plist[j-1],end='')
        plist[j]=plist[j]+plist[j-1]
        #print(plist)
    print("行號:",i,plist)

幾層:10
行號: 1 [1]
行號: 2 [1, 1]
行號: 3 [1, 2, 1]
行號: 4 [1, 3, 3, 1]
行號: 5 [1, 4, 6, 4, 1]
行號: 6 [1, 5, 10, 10, 5, 1]
行號: 7 [1, 6, 15, 20, 15, 6, 1]
行號: 8 [1, 7, 21, 35, 35, 21, 7, 1]
行號: 9 [1, 8, 28, 56, 70, 56, 28, 8, 1]
行號: 10 [1, 9, 36, 84, 126, 126, 84, 36, 9, 1]









四則運算 中序轉後序








2020年1月27日 星期一

Python基礎 --Python 網路爬蟲王者 --佳魁資訊


-------------------------------------- 開始之前

IDLE Python GUI 是一個功能完備的程式 IDE ( Integrated Development Environment 整合式開環境 )
Python Shell Python 的互動模式

Tab 建,自動補全關鍵字
Alt + P 回復到上一次編輯的 Python 程式
Alt + N 相反



--------------------------------------3.1 Python 哲學

>>> import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

提姆·彼得斯(Tim Peters)撰寫的《 Python之禪》
美麗勝於醜陋。
顯式勝於隱式。
簡單勝於復雜。
複雜勝於復雜。
扁平比嵌套更好。
稀疏勝於密集。
可讀性很重要。
特殊情況還不足以打破規則。
儘管實用性勝過純度。
錯誤絕不能默默傳遞。
除非明確地保持沉默。
面對模棱兩可的想法,拒絕猜測的誘惑。
應該有一種-最好只有一種-顯而易見的方法。
儘管除非您是荷蘭人,否則一開始這種方式可能並不明顯。
現在總比沒有好。
儘管從來沒有比現在“正確”好。
如果實現難以解釋,那是個壞主意。
如果實現易於解釋,則可能是個好主意。
命名空間是一個很棒的主意-讓我們做更多這些吧!



--------------------------------------3.2 輸入與輸出
3.2.1 print

>>> print("Hello Python!")
Hello Python!


name="kk"
print("Hello %s ,Nice to meet you!" %name)        # %s 字串

Hello kk ,Nice to meet you!


age=27
print("You are %d !" %age)        # %d 數字

You are 27 !



n=100
print("You print is %r !" %n)        # %r 不知列印類型

n="ABC"
print("You print is %r !" %n)

You print is 100 !
You print is 'ABC' !





3.2.2 input

n=input("Enter any content:")
print ("Your input is %r" %n)

Enter any content:Tom
Your input is 'Tom'



3.2.3 引號與註釋

Python 不區分單引號與雙引號

# 單行註釋

"""或 ''' 三個引號表示多行註釋,不區分單引號與雙引號




--------------------------------------3.3 分支與循環
3.3.1 if 敘述

a=2
b=3
if a>b:
    print("a max!")
else:
    print("b is max!")

b is max!



name="Tom"
if name=="Tom":        # 相等 == , 不相等 !=
    print("Tom,you are on duty today.")
else:
    print("Please call Tom to duty")

Tom,you are on duty today.



string="Hello World"
if "Hello" in string:        # not in 表示不包含
    print("Contain")
else:
    print("Not Contain")

Contain


a=True
if a:
    print("a is True")
else:
    print("a is not True")

a is True



results=72
if results >= 90:
    print('優秀')
elif results >= 70:
    print('良好')
elif results >= 60:
    print('及格')
else:
    print('不及格') 

良好



3.3.2 for 敘述

for i in "Hello World":
    print(i)

H
e
l
l
o
W
o
r
l
d



fruits=["banana","apple","mango"]        #字典
for i in fruits:
    print(i)

banana
apple
mango


for i in range(4+1):        #進行一定次數的循環
    print(i)

0
1
2
3
4


#range(start,end[,step])預設從0開始循環,也可設定起始位置和步進值,Python3 range()是一個陣列
for i in range(1,9+1,2):        
    print(i)

1
3
5
7
9



--------------------------------------3.4陣列 [ ]與字典 { }

3.4.1 陣列

>>> lists=[1,2,3,'a',5]
>>> lists
[1, 2, 3, 'a', 5]
>>> lists[0]
1
>>> lists[4]
5
>>> lists[4]='b'
>>> lists[4]
'b'
>>> lists.append('c')
>>> lists
[1, 2, 3, 'a', 'b', 'c']



3.4.2 字典

>>> dicts={'na':'Tom','pwd':123456}
>>> dicts.keys()
dict_keys(['na', 'pwd'])
>>> dicts.values()
dict_values(['Tom', 123456])
>>> dicts.items()
dict_items([('na', 'Tom'), ('pwd', 123456)])


>>> for i in dicts.items():
print(i)

('na', 'Tom')
('pwd', 123456)


>>> for k,v in dicts.items():
print("dicts key is  %r" %k)
print("dicts values is  %r" %v)

dicts key is  'na'
dicts values is  'Tom'
dicts key is  'pwd'
dicts values is  123456



>>> key=['b','a','c','e','d']
>>> value=['2','1','3','5','4']

>>> for k,v in zip(key,value):        #zip 方法合併2個 List 為 Dictionary
print(k,v)


b 2
a 1
c 3
e 5
d 4



-------------------------------------- 3.5 函數、類別和方法
3.5.1 函數

def add(a,b):
    print(a+b)

add(3,5)

8



def add(a,b):
    return (a+b)

print(add(3,5))

8



def add(a=1,b=2):
    return a+b

print(add())        #沒傳參數就使用預設參數
print(add(3,5))

3
8



3.5.2 類別和方法

#class A(object): 所有類別預設繼承 object,所以不宣告也可以
class A():

#方法第一個參數必須存在,一般習慣命名 self,呼叫方法時不需為這參數傳值
    def add(self,a,b):     

        return a+b

cnt=A()
print(cnt.add(3,5))

8



class A():
#建立類別時首先宣告初始化的方法 _ _init_ _
    def __init__(self,a,b):
        self.a=int(a)
        self.b=int(b)
     
    def add(self):
        return self.a+self.b 

cnt=A('4',5)
print(cnt.add())

9




class A():
    def add(self,a,b):
        return a+b 

class B(A):        #B類別繼承A類別
    def sub(self,a,b):
        return a-b
 
print(B().add(3,5))

8





-------------------------------------- 3.6 模組

3.6.1 參考模組

>>> import time
>>> help(time)
Help on built-in module time:
.
.
.


>>> print(time.ctime())
Fri Jan 24 08:51:44 2020



>>> from time import ctime
>>> print(ctime())
Fri Jan 24 08:53:48 2020





from time import *

print(ctime())
print("休眠2秒")
sleep(2)
print(ctime())

Fri Jan 24 08:57:56 2020
休眠2秒
Fri Jan 24 08:57:58 2020






3.6.2 模組呼叫

# project/pub.py
def add(a,b):
    return a+b


# project/count.py
from pub import add
print(add(4,5))

9

# 在 project/ 下多了一個檔案 __pycache__/pub.cpython-38.pyc 預先編譯的模組,為了加強模組載入速度






3.6.3 跨目錄模組呼叫

# project/model/pub.py
def add(a,b):
    return a+b


# project/count.py
from model.pub import add
print(add(4,5))

9





3.6.4  進一步討論跨目錄模組呼叫

# \project\model\count.py
class A():
    def add(self,a,b):
        return a+b


# \project\model\new_count.py
from .count import A
class B(A):
    def sub(self,a,b):
        return a-b

resule=B().add(2,5)
print(resule)


# \project\test.py
import sys
sys.path.append("./model")
from model import new_count
test=new_count.B()
test.add(2,5)

7




-------------------------------------- 3.7 例外

3.7.1 認識例外

Python 用例外物件 exception object 來表示例外情況 ,遇到錯誤後會引發例外。如果例外物件並未處理或捕捉,則程式就會用回溯 Traceback 來終止執行。

>>> open("abc.txt",'r')
Traceback (most recent call last):
  File "<pyshell#0>", line 1, in <module>
    open("abc.txt",'r')
FileNotFoundError: [Errno 2] No such file or directory: 'abc.txt'

# 透過 open() 方法,以讀 'r' 的方式開啟不存在的檔案


try:
    open("abc.txt",'r')
except FileNotFoundError:
    print("例外了!")

例外了!



>>> print(aa)
Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    print(aa)
NameError: name 'aa' is not defined

try:
    open(aa)
except NameError:
    print("例外了!")

例外了!


在 Python 中所有的例外類別都繼承 BaseException,所以可使用它來接收所有類型例外

try:
    open(aa)
except BaseException:
    print("例外了!")

例外了!



# 告訴我們例外的原因
try:
    print(aa)
except BaseException as msg:
    print(msg)

name 'aa' is not defined




3.7.2 更多例外用法

try:
    print(aa)
except BaseException as msg:
    print(msg)
else:
    print("沒有例外!")

name 'aa' is not defined



try:
    aa="例外測試"
    print(aa)
except BaseException as msg:
    print(msg)
else:
    print("沒有例外!")

例外測試
沒有例外!




try:
    aa="例外測試"
    print(aa)
except BaseException as msg:
    print(msg)
else:
    print("沒有例外!")
finally:
    print("不管是否例外,都會被執行。")

例外測試
沒有例外!
不管是否例外,都會被執行。




3.7.3 拋出例外

from random import randint
N=randint(1,9)
if N%2==0:
    raise BaseException("%d is even" %N)
else:
    raise BaseException("%d is odd" %N)

Traceback (most recent call last):
  File "C:/Users/kk/Desktop/0.py", line 4, in <module>
    raise BaseException("%d is even" %N)
BaseException: 8 is even







--------------------------------------