PowerShell

PowerShell là gì: Hiểu đơn giản nó tường tự như là Bash trên môi trường Window. Được viết trên nền .Net

Đặc điểm: Coi mọi thứ là đối tượng, hỗ trợ đường ống => hơi khó giải thích. Thao tác chủ yếu với text.

Ai dùng: Quản trị viên, những ông không thích dùng giao diện chậm chạp và chán ngắt... để tự động hoá một loạt các thao tác, quản lý hệ thống, lên lịch, tạo báo cáo...


# Cài đặt module trên PowerShell:

  • Chạy PS với quyền Administrator và cài các gói sau:
  • Install-Module MSOnline
  • Install-Module AzureAD
  • Install-Module AzureRM

# Connect service:

  • $msolcred = Get-Credential # Lưu cred để không phải đăng nhập nhiều
  • Connect-MsolService -Credential $msolcred
  • Get-MsolAccountSku # Show licences
  • Get-MsolUser -UserPrincipalName duc1514064@nuce.edu.vn

# LẦN 1 - TẠO  ALL NHƯNG BỊ LỖI 223 SV CHƯA CÓ MẬT KHẨU:

  • Import-Csv -Path "C:\Users\Thinkpad\Desktop\create.csv" | foreach { New-MsolUser -FirstName $_.FirstName -LastName $_.LastName -DisplayName $_.DisplayName -UserPrincipalName $_.UserPrincipalName -Password $_.Password -UsageLocation $_.UsageLocation -LicenseAssignment "nuceedu:STANDARDWOFFPACK_IW_STUDENT" -Department $_.Department -Title $_.Title -MobilePhone $_.MobilePhone -StreetAddress $_.StreetAddress -City $_.City -State $_.State -PostalCode $_.PostalCode -Country $_.Country -ForceChangePassword $false -StrongPasswordRequired $false } | Export-Csv -Path "C:\Users\Thinkpad\Desktop\created.csv"

# LẦN 2 - TẠO 223 SV CHƯA CÓ MẬT KHẨU:

  • Import-Csv -Path "C:\Users\Thinkpad\Desktop\223user.csv" | foreach { New-MsolUser -FirstName $_.FirstName -LastName $_.LastName -DisplayName $_.DisplayName -UserPrincipalName $_.UserPrincipalName -UsageLocation $_.UsageLocation -LicenseAssignment "nuceedu:STANDARDWOFFPACK_IW_STUDENT" -Department $_.Department -Title $_.Title -MobilePhone $_.MobilePhone -StreetAddress $_.StreetAddress -City $_.City -State $_.State -PostalCode $_.PostalCode -Country $_.Country -ForceChangePassword $false -StrongPasswordRequired $false } | Export-Csv -Path "C:\Users\Thinkpad\Desktop\223user-log.csv"

# LẦN 3 - SET LẠI TÊN 581 user & LICENSES:

  • Import-Csv -Path "C:\Users\Thinkpad\Desktop\setName.csv" | foreach { Set-MsolUser -UserPrincipalName $_.UserPrincipalName -FirstName $_.FirstName -LastName $_.LastName -DisplayName $_.DisplayName  -UsageLocation $_.UsageLocation -Department $_.Department -Title $_.Title -MobilePhone $_.MobilePhone -StreetAddress $_.StreetAddress -City $_.City -State $_.State -PostalCode $_.PostalCode -Country $_.Country }
  • Import-Csv -Path "C:\Users\Thinkpad\Desktop\create.csv" | foreach { Set-MsolUserLicense -UserPrincipalName $_.UserPrincipalName -AddLicenses "nuceedu:STANDARDWOFFPACK_IW_STUDENT" }

# RESET PASS:

  • Set-MsolUserPassword -UserPrincipalName lichcongtac@nuce.edu.vn -NewPassword dhxd1234 -ForceChangePassword $False

# GROUP OFFICE 365 (MS TEAMS):

# THAM KHẢO:


THAO TÁC VỚI GSUITE QUA DÒNG LỆNH (Cmd.exe và PowerShell)

(Yêu cầu phải tạo App OAuth cho phép gọi Api Services trên console.developers.google.com/)

# Một là dùng GAM (Google Admin Mananger) chạy qua cmd.exe, ko biết cầu hình qua PowerShell hay Bash kiểu gì:

# Hai có thể dùng PSGSuite (Power Support Gsuite) chạy qua PowerShell:

  • Lưu ý: chỉ thao tác được với loại PowerShell khi cài đặt Module, nếu cài trên PS 7.1  dùng PS 5.1 ko thao tác được.

# Phục hồi email dat46862@nuce.edu.vn

# Các câu lệnh hay dùng

  • Update-GSUser [-User]  [-PrimaryEmail ] [-FullName ] [-Password ] [-ChangePasswordAtNextLogin] [-OrgUnitPath ] [-Suspended] [-Addresses ] [-Emails ] [-ExternalIds ] [-Ims ] [-Locations ] [-Organizations ] [-Relations ] [-RecoveryEmail ] [-RecoveryPhone ] [-Phones ] [-IncludeInGlobalAddressList] [-IpWhitelisted] [-IsAdmin] [-Archived] [-CustomSchemas ] [-WhatIf] [-Confirm] []

# Lấy thông tin người dùng

# Cập nhật số điện thoại và email phục hồi:

# Công thức Google sheet

  • =CONCATENATE("Update-GSUser -User ", C9, " -Password (ConvertTo-SecureString  ", char(34),J9, char(34), " -AsPlainText -Force) -ChangePasswordAtNextLogin:$false -Confirm:$false")

# Reset password a user

  • Update-GSUser -User anhtth@nuce.edu.vn -Password (ConvertTo-SecureString  "22081987@anh" -AsPlainText -Force) -ChangePasswordAtNextLogin:$false -Confirm:$false

 

 


Đây là một số bước cơ bản mà Quản trị Server thường làm vào mỗi ngày. Yêu cầu biết sử dụng CLI, SSH, một ít kiến thức về LPI

 

BACKUP SITE
----------------------------------------------------------

  • # find . -name \*.zip  //Tìm kiếm file đuôi zip
  • # find . -name '*.css' -exec grep -i 'btn--google' {} \; -print   //Tìm kiếm file css có chứa ký tự btn--google
  • # mysqldump -u user_db -p database > database_luu.sql  //Xuất DB ra file để backup
  • # zip -r site_bakup.zip thumuc_nen/*   //Nén rồi đẩy lên Drive
  • /var/www/html/moodledata/localcache/core_admin/1586257922/logo/0x150

 

KHỞI TẠO SITE
----------------------------------------------------------

Bước 1: Tạo thư mục dir, đẩy source lên hoặc wget data về thư mục

  • Apache:  /var/www/
  • Nginx: /home/nginx/domains/
  • unzip /path/to/file.zip -d temp_for_zip_extract

Bước 2: Tạo mới rồi Import file database_luu.sql vào Cơ sở dữ liệu

  • mysql -u root -p password_root
  • > CREATE DATABASE ten_database CHARACTER SET utf8 COLLATE utf8mb4_general_ci;  // Tạo Cơ sở dữ liệu
    > CREATE USER 'user_db'@'localhost' IDENTIFIED BY 'password_user'; // Tạo user_db sql có mật khẩu là password_user
    > GRANT ALL PRIVILEGES ON ten_database.* TO 'user_db'@'localhost' WITH GRANT OPTION; // Gán quyền user vào ten_database
    > FLUSH PRIVILEGES;
  • mysql -u user_db -p -h localhost ten_database < /DIR/database_luu.sql // Import CSDL
  • Nếu bị ERROR 2006 (HY000)
    > set global max_allowed_packet=1024*1024*120;
    
    Error 1709: Index column size too large. The maximum column size is 767 bytes.
    > SET GLOBAL innodb_large_prefix = ON;
    > SET GLOBAL innodb_file_format=Barracuda;
    > SET GLOBAL innodb_file_per_table=ON;
     

Bước 3: Cấu hình file config

Với Apache:

- Mặc định vào: /etc/httpd/conf.d tạo file tensite.conf hoặc xem thư mục gốc trong file /etc/httpd/conf/httpd.conf

   ServerAdmin admin@tensite.com
   DocumentRoot /var/www/thư_mục_chứa_code
   ServerName tensite.com
   ServerAlias www.tensite.com
   
       Options FollowSymLinks
       AllowOverride All
       Order allow,deny
       allow from all
   
   ErrorLog /var/log/httpd/tensite.com-error_log
   CustomLog /var/log/httpd/tensite.com-access_log common

Với Nginx, PHP-FPM:

Tạo file: /usr/local/nginx/conf/conf.d/ten_site.com.conf

server {
  server_name ten_site.com www.ten_site.com;
  add_header X-Xss-Protection "1; mode=block" always;
  add_header X-Content-Type-Options "nosniff" always;
  access_log /home/nginx/domains/ten_site.com/log/access.log combined buffer=256k flush=5m;
  error_log /home/nginx/domains/ten_site.com/log/error.log;
  include /usr/local/nginx/conf/autoprotect/ten_site.com/autoprotect-ten_site.com.conf;

  # Thư mục đặt source code
  root /home/nginx/domains/ten_site.com/public;
  include /usr/local/nginx/conf/503include-main.conf;

  # quang Hiển thị ảnh với Drupal
  location @rewrite {
    rewrite ^ /index.php last;
  }
  location ~* files/styles {
    access_log off;
    expires 30d;
    try_files $uri @rewrite;
  }
  location / {
    try_files $uri $uri/ /index.php?$args;
    include /usr/local/nginx/conf/503include-only.conf;
  # quang Hiển thị ảnh với Drupal
}

include /usr/local/nginx/conf/pre-staticfiles-local-ten_site.com.conf;
include /usr/local/nginx/conf/pre-staticfiles-global.conf;
include /usr/local/nginx/conf/staticfiles.conf;
include /usr/local/nginx/conf/php.conf;
include /usr/local/nginx/conf/drop.conf;
include /usr/local/nginx/conf/vts_server.conf;
}

Kiểm tra lại cấu hình Apache hoặc Nginx

  • # apachectl configest // Kiểm tra tương thích
  • # systemctl restart httpd.service // Khởi động lại Server Apache
  • # systemctl restart nginx  // Khởi động lại Nginx

Bước 4: Kiểm tra lại Firewall đã mở cổng 80 và 443 chưa

  • # firewall-cmd --permanent --zone=public --add-service=http
  • # firewall-cmd --permanent --zone=public --add-service=https
  • # firewall-cmd --reload

 

yum -y install mod_ssl

mkdir -p /etc/ssl/private

chmod 700 /etc/ssl/private

sudo vi /etc/httpd/conf.d/ssl.conf


ServerName www.example.com
Redirect "/" "https://www.example.com/"


443>
DocumentRoot /var/www/html
ServerName www.example.com
SSLEngine on
SSLCertificateFile /etc/ssl/private/certificate.crt
SSLCertificateKeyFile /etc/ssl/private/private.key

apachectl configtest

/var/www/html/moodledata/localcache/core_admin/1586257922/logo/0x150 http://cms.nuce.edu.vn/pluginfile.php/1/core_admin/log… ---------------------------------------------- #!/bin/bash LOCALFOLDER=/backup GFOLDERID=0B5I8-U7RcQGieF9rYmNudkkwQWM for i in $(ls $LOCALFOLDER) do drive upload --file /backup/$i -p $GFOLDERID done ---------------------------------------------- # Thêm user adduser quangtv passwd quangtv # Phân quyền root visudo ## Allow root to run any commands anywhere root ALL=(ALL) ALL quangtv ALL=(ALL) ALL :wq # Bước 1: Tạo file Bash nano /home/quangtv/ ----------Bắt đầu nội dung file bash---------- #!/bin/bash # BACKUP DATABASE db_name=tttt db_user=root db_password='@#$%^&*7' backup_filename=$db_name-`date +%F` mysqldump -h localhost -u $db_user -p$db_password $db_name | gzip > /var/www/tttt.nuce.edu.vn/$backup_filename.sql.gz # BACK CA THU MUC destination_folder=/home/quangtv/backup archive_file="tttt.nuce.edu.vn.bak-`date +%F`.tar.gz" # mkdir -p $destination_folder /bin/tar -czvf $destination_folder/$archive_file /var/www/tttt.nuce.edu.vn --exclude='/home/quangtv/backup' ----------Kết thúc nội dung file bash---------- # Bước 2: Tạo lịch hàng ngày crontab -e # Run backup at 03:00hrs every day 03 03 * * * /bin/sh /home/quangtv/backup-site-tttt.sh 2>&1 >> /var/log/tttt_backup.log

https://unix.stackexchange.com/questions/185764/how-do-i-get-the-size-of-a-directory-on-the-command-line

 

Get link image JS: http://jsfiddle.net/mplungjan/u92Ra/

(function(){
      var imgs = document.getElementsByTagName('img'),t=[];
      for (var i=0, n=imgs.length;i'+file+''); 
        t.push('
');
        
      }  
      if (t.length) {
        var w=window.open('','_blank'); 
        if (w) {w.document.write(t.join(' ')); w.document.close();}
        else alert('cannot pop a window');  
      }    
     })();

Cấu hình SSL Let's Encrypt cho trang web trên LAMP

 

Cài chứng chỉ SSL Free trên Centos 7

Bước 1: cài LAMP cấu hình site các kiểu chạy ngon lành...

Bước 2: Cài chứng chỉ Let's Encrypt miễn phí 3 tháng.
- Bật firewall cho giao thức http, https qua:

  • # firewall-cmd --permanent --zone=public --add-service=http

  • # firewall-cmd --permanent --zone=public --add-service=https

  • # firewall-cmd --reload

- Cài Certbot

  • # yum install epel-release
  • # yum install certbot certbot-apache mod_ssl -y
  • # certbot --apache -d tttt.nuce.edu.vn

- Điền email, A, Y, 2
- Thành công sẽ có thông báo key sẽ nằm trong: /etc/letsencrypt/live/tttt.nuce.edu.vn
- Đồng thời certbot sẽ cấu hình lại ssl trên file conf của site và /etc/httpd/conf.d/ssl/conf

- Kiểm tra cấu hình apache, khởi động lại.

  • # apachectl configest
  • # systemctl restart httpd.service

- Vào https://www.ssllabs.com/ssltest kiểm tra lại trạng thái đạt A,B là ok
- Nếu trong site vẫn còn link http thì biểu tượng ổ khoá trên trình duyệt sẽ có cảnh báo. F12 để check lại link http và sửa chữa nó.

- Chú ý: chứng chỉ có hạn trong 3 tháng, hết hạn muốn cấp lại hoặc đặt cron cho hệ thống tự chạy

  • # certbot renew
  • # cron -e 
  • #Insert cập nhật hàng ngày  > cân nhắc
  • 0 0 * * * /usr/bin/certbot renew &>/var/log/certbot.cronlog
  • # cron -l => xem danh sách cron

- Bật chạy lúc khởi động

  • # systemctl start certbot-renew.timer
  • # systemctl enable certbot-renew.service
  • # systemctl list-timers
  • # systemctl start certbot-renew.service
  • # systemctl status certbot-renew.service
  • # systemctl enable certbot-renew.service