我需要做什麼才能允許遠端存取 Unbuntu 20.04 Server 上的 MySQL?

我需要做什麼才能允許遠端存取 Unbuntu 20.04 Server 上的 MySQL?

我有一個 Python 腳本,用於從 allstudentsAnswers20BE 表中收集學生的作業和線上課堂作業分數。

這在我的舊共享網站寄存網頁上效果很好。

在新的 Ubuntu 20.04 雲端伺服器上,我收到連線被拒絕的訊息。我沒有運行雲端伺服器的經驗。

我在 UFW 中允許連接埠 33060 和 3306

我家ip不固定。

當我運行 Python 腳本時,嘗試連接到雲端伺服器時出現此錯誤

pymysql.err.OperationalError: (1130, "183.206.16.30' 不允許連接到此 MySQL 伺服器")

netstat 說 mysqld 正在監聽 33060 和 3306,所以我在防火牆 ufw 中允許這兩個端口

透過 ssh 連接到雲端伺服器,我運行:

sudo nano /etc/mysql/mysql.conf.d/mysqld.cnf

我將綁定地址行更改為 0.0.0.0 (我也嘗試過*)

我重新啟動了mysql: sudo systemctl restart mysql

伺服器端肯定還有其他需要設定的東西。

請提供任何提示,我真的需要它才能工作。

我也得到了這個資訊(假設我的雲IP是123.456.789.123):

pedro@ebs-105422:~$ nc -v -w 2 123.456.789.123 3306
連接到 123.456.789.123 3306 連接埠 [tcp/mysql] 成功! pedro@ebs-105422:~$

這是否意味著 mysqld 正在監聽 3530?還是這是mysqld的PID?

pedro@ebs-105422:~$ sudo netstat -tap | grep mysql tcp 0 0 0.0.0.0:mysql 0.0.0.0:* 監聽 3530/mysqld
tcp6 0 0 [::]:33060 [::]:* 監聽 3530/mysqld
pedro@ebs-105422:~

下面是來自伺服器上的mysql,確認埠3306

mysql> 顯示變量,其中variable_name in ('主機名稱','連接埠');
+----------------+------------+
|變數名 |價值|
+----------------+------------+
|主機名稱 | ebs-105422 |
|港口| 3306| +-------------+------------+
2 行一組(0.01 秒)

mysql>

答案1

我想通了,這個答案只是為了幫助那些可能遇到同樣問題的人。這種方式可能不太安全,因為3306是開放的,但是a)我只有作業b)你仍然需要使用者名稱和密碼。

當您在 mysql 上建立使用者時,它看起來像這樣,當您透過伺服器上的 ssh 執行此操作時也是如此:

建立由「密碼」標識的使用者「peter」@「localhost」;
將 some_db.* 上的所有權限授予 'peter'@'localhost';

如果要遠端訪問,則需要更改使用者資料(或建立新使用者):

將使用者“peter”@“localhost”重新命名為“peter”@“%”;
將 somedb.* 上的所有內容授予 'peter'@'%';

% 這裡顯然代表任何ip

然後在伺服器上也透過 ssh:

sudo nano /etc/mysql/mysql.conf.d/mysqld.cnf

找到有的行

綁定位址 = 127.0.0.1

將此更改為

綁定位址 = 0.0.0.0

ctrl X 退出 nano nano 詢問是否要儲存,按 y,然後輸入儲存在您開啟的位置 /etc/mysql/mysql.conf.d/mysqld.cnf

然後(在伺服器上):

sudo systemctl 重新啟動 mysql

之後,我的 Python 在 Idle shell 中運作良好:

def mysqlRemoteAttn(clas): 
    # To connect remote MySQL database 
    conn = pymysql.connect( 
        host='123.456.789.123',
        port=3306,
        user='myusername',  
        password = 'mypassword', 
        db='allstudentsdb', 
        ) 
      
    cur = conn.cursor()

    sql = f"SELECT studentnr, attn_this_week FROM allstudents{clas}"
    cur.execute(sql)
    output = cur.fetchall()           
            
    # To close the connection 
    conn.close()
    return output

# get the attendance from the webpage MySQL
results = mysqlRemoteAttn(clas)

相關內容