Python Tutorial: Write a Script to Monitor a Website, Send Alert Emails, and Reboot Servers
45:59

Python Tutorial: Write a Script to Monitor a Website, Send Alert Emails, and Reboot Servers

Corey Schafer 04.03.2019 161 127 просмотров 2 985 лайков

Machine-readable: Markdown · JSON API · Site index

Поделиться Telegram VK Бот
Транскрипт Скачать .md
Анализ с AI
Описание видео
In this Python Programming Tutorial, we're going to be looking at a real-world example of writing a script to monitor a website. If the website doesn't return a successful response for any reason then we will send an email and reboot the web server. Let's get started... The code from this video (with added logging) can be found at: http://bit.ly/monitor-script Google Account Settings: https://myaccount.google.com/lesssecureapps https://myaccount.google.com/apppasswords Requests Video - https://youtu.be/tb8gHvYlCFs Environment Variables (Windows) - https://youtu.be/IolxqkL7cD8 Environment Variables (Mac and Linux) - https://youtu.be/5iWhQWVXosU Try/Except Video - https://youtu.be/NIWwJbo-9_8 F-String Video - https://youtu.be/nghuHvKLhJA Crontab Video - https://youtu.be/QZJ1drMQz1A ✅ Support My Channel Through Patreon: https://www.patreon.com/coreyms ✅ Become a Channel Member: https://www.youtube.com/channel/UCCezIgC97PvUuR4_gbFUs5g/join ✅ One-Time Contribution Through PayPal: https://goo.gl/649HFY ✅ Cryptocurrency Donations: Bitcoin Wallet - 3MPH8oY2EAgbLVy7RBMinwcBntggi7qeG3 Ethereum Wallet - 0x151649418616068fB46C3598083817101d3bCD33 Litecoin Wallet - MPvEBY5fxGkmPQgocfJbxP6EmTo5UUXMot ✅ Corey's Public Amazon Wishlist http://a.co/inIyro1 ✅ Equipment I Use and Books I Recommend: https://www.amazon.com/shop/coreyschafer ▶️ You Can Find Me On: My Website - http://coreyms.com/ My Second Channel - https://www.youtube.com/c/coreymschafer Facebook - https://www.facebook.com/CoreyMSchafer Twitter - https://twitter.com/CoreyMSchafer Instagram - https://www.instagram.com/coreymschafer/ #Python

Оглавление (8 сегментов)

<Untitled Chapter 1>

hey there how's it going everybody in this video I'm gonna write a quick and easy script that monitors my personal website and sends me an email if it's down for any reason now if the site is down then I'm also going to have it have the script automatically restart my server to see if that fixes the problem now a lot of people have wanted me to make videos on real-world problems that I can solve with programming and this is a strip that I've been needing to write for a while now so my personal website runs on a server that is pretty old at this point and it really just needs to be completely wiped and updated so that it's more stable but it's one of those things that I just haven't had the time to do but with the server in its current state sometimes web processes occasionally quit unexpectedly and cause my website not to load now for those of you who have followed along with either my flask or Django series then don't worry the servers that we set up in that series are completely fine and stable this is just a server that I set up years and years ago that I used to test a lot of different software and development and then I just plot my personal website on there so after all those years of having different configurations and installations it's just not very stable anymore so until I can get around to updating that I'm just gonna write a quick script that occasionally checks my website and if it's not returning a 200 response which means that it was a successful response then I'll just have it send me an email so that I know I need to go fix it now this website is hosted on low note so I also use the node API to automatically restart the server so that it possibly fixes itself before I even get the email so this is going to be a pretty quick and easy script but I thought some of you might find it useful to see me write this up now I'm not gonna go into as much step-by-step detail as to exactly what I'm doing like I do in my other tutorials I'm just going to step through this quickly and give you an idea of how a quick script can help you solve a real-world problem like this so let's go ahead and get started so first of all I'm going to create a directory of everything for this little project so I'm in my home folder within my terminal and I'm going to create a directory called site monitor so I'm gonna say m'kay der site underscore monitor now I'm on a Mac which mostly uses the Linux commands if you're on Windows then you'll have to either do this through your file explorer or use the windows for your command prompt okay so I'm going to CD into that directory that I just created and I'm going to create a

Create a Virtual Environment

virtual environment for this little project now I've been using the V env module in the Python standard library lately instead of virtual Envy and it's pretty simple to use and you don't have to install anything so I can just say Python 3 - M de and V and then I'll call this virtual environment Monitor underscore env so I will run that so now I have a new virtual environment called monitor underscore env so now I can activate that so I'll say source monitor E and V /bin board slash activate so that is now activated we can see from the prompt here that it's active and again this source command is for Mac and Linux if you're on Windows then you would do something like this you'd say monitor env back slash scripts back slash activate dot bat or something like that I think that's right but this is on Mac and Linux okay so now I have a fresh environment and I'm going to be using a couple of packages for this script so I'm going to use the request library to check the response from my website and I do have a more in-depth video on the request library if you'd like to see how to use this in more detail so I'll leave a link to that video in the description section below and I'm also going to be using the lonoa thon library to interact with my server so I have this open here in the browser and let me go to that documentation here so this is the low note Python library that allows you to interact with your low notes through Python and we'll see more about this later in the tutorial so now we want to install both of those packages and we can do that through pip so once we've got the environment activated let's pip

Pip Install

install these packages so first I'll install the request library so I'll say pip install requests and this one is usually pretty quick okay that's done and also I want to install the Lund ode Python library that I can use to talk to my low note servers through Python so to do that I can say pip install and that is the node underscore API for now if you want to know how I got that it's here in their documentation pip install the node API for so let me run that now with this lonoa thawne library we're gonna need a personal access token in order to interact with our lenôtre count and that's good because it's a layer of security that makes us prove who we are before doing anything with our servers so but let's go ahead and continue on with the email script for now and I'll grab that personal access token once we're ready to interact with the low note server okay so now that we have those packages installed let's actually write the scrip to monitor the website so I'm still here within my directory for this project so I'm going to open this up in sublime so I'm just going to do that with su BL and then dot for the current directory now I have my command-line shortcut set up to open sublime with that su BL command if you don't have that then you can just open this directory and your text editor like you normally would

Create a New Script

okay so now I'm going to create a new script in this directory so new file and I'm going to call this monitor dot py so now we have an empty Python script here okay so first I'm going to import the request library okay so now we're going to use request to make a request to my home page so we can do that by saying R is equal to request dot get and this needs to be in a string here so this is HTTP forge slashes query MS dot-com and I'm going to set a timeout there equal to let's say five seconds now you want to set a timeout when doing something like this because if your site isn't responding and it gets hung up then by default the request library will just wait indefinitely so with a timeout set it will only wait that number of seconds that you specified before giving up and throwing an exception so if my site doesn't respond in five seconds then I'll just assume that something's up okay so now I'm going to check to make sure that the response of that request has a status code of 200 so 200 response is a successful response and if the response is an 200 response then I'll want to send myself an email and restart my server so I'm gonna say if our dot status whoops let me spell that right status underscore code is not equal to 200 now the response object also has an attribute called okay which is set to true if the response is less than 400 so I could have also written that like this if not our dot okay but that okay value would be true for any response that isn't you know a 400 or 500 error and I know for sure that I'm expecting a 200 response so that's what I'm checking for specifically so I'm not using that okay value that you may have seen in other tutorials okay so if the response isn't a 200 response then first I want to send myself an email letting me know that something is up so to do this we're going to need to use a mail server so I'm going to use my gmail account but you can use whatever you'd like so whatever you use you'll have to look up the instructions online for how to connect to that server so it's pretty simple for Gmail you do need to let Gmail know that you're going to be connecting to your account through a program and I have the instructions pulled up here in the browser as well so if you don't have to factor authentication then you can just go to your Google settings and allow connection through less secure apps so this is at my account Google comm ford slash less secure apps and I'll put links to these in the description sections below but I do have two factor authentication on my machine so in order to connect to your account while you have two-factor authentication then you're going to need to create a password specifically for our app and you can do that through this account here my account Google comm forward slash app passwords and I will put a link to this URL in the description section below as well and you can see here that in my app passwords I created one called Python tests that I use for connecting through Python applications now like I said I'll put a link in the description section below to both of these Google pages if you want to know how to set this up for yourself so once you have your Google security settings in order then

Connect to the Google Mail Server

we connect to the Google Mail server with the built-in SMTP Lib module in Python so first I'm going to import that at the top of our script so I'll pull this back up and right above request I'm going to say import SMTP Lib and save that and now to set this up to send an email within my conditional here I'm going to say with SMTP Lib dot SMTP and the mail server here is going to be smtp. gmail. com and for the second argument we pass in the port so this is going to be 587 and this is on their documentation online so I don't actually memorize this stuff I have references to this how this works okay so now we have this SMTP connection to their mail server so now we're gonna say SMTP now the e hlo method just identifies ourselves with the mail server that we're using and now we want to encrypt our traffic so to do that I can say SMTP what not SMTP Lib SMTP dot start TLS and that's going to be a method and then we need to rerun that eh ello method again to re identify ourselves as an encrypted connection so I would just copy that and paste it in there okay and now that we're encrypted we can login to our mail server so I'm going to come down here and say SMTP dot in and now at this point we can put in our email address and password now you can put this directly in the script if you'd like but I think it's a good habit never to put sensitive information like this into a script directly I think that you should always put sensitive information like this either in a configuration file somewhere that isn't committed to source code or in environment variables so for this video I've put my credentials inside environment variables so that I don't have to write them out here on video for everyone to see now if you've never used environment variables to hide information like this then I do have a separate video to show how to do that for Mac Linux and Windows so I'll leave a link to those videos in the description section below if anyone would like to see how that's done but I've already put those environment variables created with that information so I can load those in by importing the OS module so up here at the top I'm going to say import OS and at the top of my file here I'm going to create some

Environment Variables

variables using those environment variables so I'm going to create one called email address and I'm going to set that equal to Oh s dot environment that's how you get environment variables and I created these called them email underscore user and now let me create another variable here called email underscore password and the environment variable for that was email underscore Pass so again you're going to have to create your own environment variables called you know for your email address and for your email password or you can put those in a configuration variable file somewhere any way that you want to do that okay so now I'm going to login to the gmail server using those credentials so that's what we pass in here to SMTP in so first I'm going to pass in the email address then I'm gonna password okay so now let's create a simple message for our email so I'm just going to create a simple plain text email in this video and I'll be doing a more advanced email video in the near future where we cover attachments and HTML messages and things like that but for this video we just want text so first I'm going to create a subject line since this will be an email about my website being down I'm gonna make it something that will catch my eye so I will just say subject is equal to and I'll just do all caps your site is down with an exclamation point there and for the body of the website I'm just going to put something here like you know make sure the server restarted and it is back up okay and now I'm going to combine at this and body into a single message so when you're constructing a plaintext email from scratch you need to add the subject as a header and then have a couple of blank lines and then put the body of the message so I'm going to do this using an EPS tring so I will just say msg is equal to and to do an F string you do F and then your string so I'll say subject and then pass in that subject and then I'll do a couple of blank lines here and now I will pass in the body and again I'm not going into as much step-by-step detail in this video but if you've never used F strings before I think that they're really nice to work with and I have any more in-depth video on that topic and I'll leave a link to that in the description section below if you'd like to learn more about those okay so now I just have to send this email now that we've created this message so I can do that here by using this format I can say sm t p dot send mail and then we're going to want to send this to the sender and the receiver and then the message so we want to put the sender here and the receiver here so for the sender we're going to want this to be the email address that we logged in as now you can put a different value there but I wouldn't recommend it you don't want to you know spoof what email this is coming from because it's against the rules first of all for imitating someone and second of all it's probably just gonna wind up in spam I mean they have things in place that catch this kind of stuff okay so we're putting the sender as the email address that we logged in as and the receiver I'm just putting as myself also so I could put the email address here as well but just to be more clear let me act like I'm actually sending this to someone different but so I'm gonna put in Cory M Schaefer at gmail. com which is my email address but that is actually the same as what this email address is as well okay so that should send our email if our site is down now we can test this by commenting out the if statement and onion denting our email section so if I do that let me just comment out the if statement for now and unand dint the email section here so there's no conditional that won't send this email so if I go ahead and run this code then we don't have any output here but if I wait a second then I should get an email that comes through so I have my gmail pulled up here on my phone and I can see that I did just get an email that came through with the message that we specified so that works well okay so now let's set this back up to how it was within the with statement so I will indent that back and uncomment out the conditional there now also I should mention that in sublime whenever you run code you have to have a build system and I have my build system set to my virtual environment that I created at the beginning of this video so that is why that worked if you don't have your build system set up to your virtual environment then you'll have to set that in sublime but if that's too much of a hassle for you then you can always come back here to your terminal and just run that manually so you could say Python monitor dot and whoops monitor dot py and run the script that way okay so let me go back to the script here okay so now we've sent ourselves an email when the site is not responding with a 200 status code but now I'm going to use the Llano di thon library to reboot my low note server so in order to interact with milah note account programmatically I'm going to need to create an API token through my account so I have my lenôtre open here let me exit out of that okay so I've got my note account open here so in order to create an API token we need to first go to our profile so to get to the profile I'm going to click on my profile picture up here at the top right and then I can go to my profile so within here we can click on the tab that says API tokens so I'm going to click on that and we can see here that we have a section for personal access tokens now I don't have any here right now but we can create

Personal Access Token

create by clicking add a personal access token so I will create one and for the label of this token I'll just call this lenôtre - Python - token and now I'm going to set the expiration date to never if you want this to be you know more secure and have expiration dates then you can set those up however you want and I'm going to give this readwrite access to everything on my account so now if I scroll down here I can submit that token and now it's going to pop up with the API access token so I'm going to copy this now this token actually won't be visible anymore after I close this so you want to be sure that you copy this down or write it down somewhere so I'm going to click OK here and now we have our a node python token here within our personal access tokens now don't worry I'm going to delete this token after the video and create a new one so that no one can access my account using this token that we saw in this video but I'll use this one for now okay so at this point I'm going to create another environment variable for this API token so I'm not going to show that here on video since my email credentials are in there also but like I said if anyone doesn't know how to set environment variables then there's a link to those videos in the description section below on how to do that okay so I'm going to pull up my terminal here and I'm going to pause the video while I add that token to my environment variables and I'll pick it up after I've added that token okay so I went in and I set an environment variable called lenôtre token to that token that I got from the node so now I can use that to interact with my lono to count through python so now let's go back to my script and I'll show you how this works so let me open the script here so first let's import that 'la note client so to do that up here at the top where we're doing our imports I can say from the node underscore API for import 'la note client and now I'm just going to grab that varmint variable that I just set and I'll just put this under the email address and password so I'll say 'la node underscore token is equal to and we'll just do another OS dot environment but this environment variable I set as 'la node underscore token now one important thing is that you usually need to restart everything after you set an environment variable so that those changes can take effect some people don't do that and then they wonder why they can't see their variable that they just set so if you haven't restarted then it's probably not going to pick up those changes so for example let me comment out everything below here and try to print out my environment variable that I just set so I'm going to print out that whoops that 'la note token and let me try to save that and run it and actually I do get a response there which I shouldn't have I should have restarted this before I started recording this video but this actually isn't the Llano token that we just created this is one that I created earlier whenever I was testing all the stuff for the video so most likely if you haven't restarted then you'll get a nun response there so once I restart this we're going to get the new token so you can see this one is 6 to be 9 5 e so when I restart this so let me restart sublime and open this back up so sublime in the current directory open that back up open my monitor script now let me run this again and we can see that now this is a different token it picked up those changes this one is 8 to b61 blah blah blah and you're gonna want to do that in your terminal as well I'm not sure let's see if I run this script now with python monitor dot py yeah so I'm still getting that old token with this terminal as well so I would have to open a new terminal and CD into that site monitor and then I would have to activate my virtual environment again so activate monitor underscore env Binh activate and now if I did Python monitor dot py ran that then we get the new token so now let me resize this here and delete this other terminal that we had open okay so now we are getting our correct token value so now I'm going to leave everything commented out below this while I show you how we can restart a low note server through Python and after we get that working then I'll put that logic in the correct place so first let's connect to the node through our client so we can do that I'm going to remove this print statement so I'm going to say client is equal to the node client that we imported right here and we need to create or pass in sorry we need to pass in this lenôtre token so we're connecting to this Linode client passing in Batlin owed token and now I'm going to print out some information about milah node servers I only have one active server at the moment so we should just see that one here but to do this I'm going to say for the node in client dot 'la note dot instances and within that for loop I'm going to print out the node label and the ID of each instance which I said will just be the one instance for now so I'll say print and I'll use an F string here again whoops an F string and I will print out first the Lynott label then I will do a colon and a space and then I will print out the Leonard I do so let's save that and run it and we can see usually it takes longer than that but we can see that it basically immediately came back with my query MS server and then this is the ID of that server now I'm gonna want to copy that ID so that I can just connect to that single instance in order to reboot it so to do that first I have to import instance up here so we are importing the note client we also want to import instance and now I'm going to copy that ID from the output so let's copy that and now I can connect to the low note with that ID just by saying and I'm going to get rid of my for loop here so we can just say my server is equal to client dot load and we want to load an instance so we're using instance that we imported there and now I'm going to pass in the ID of the instance that we want to connect to so now that I've loaded that particular load I should be able to reboot that machine simply by saying my server dot reboot so let me make this output a little bit smaller here so that we can see a little bit more so now I'm going to run this and I'm going to open up Milan ode account and check that machine is actually rebooting so I will save that and run it so it should be rebooting that server with that ID so let me open up Milan ode account here go to my dashboard now it doesn't look like it is rebooting yet but let me click on there and this will give me details and we can see that the details here it actually does say that it's rebooting now so that did work in that script so sometimes that can take a bit before that reboot actually gets triggered but if we wait for a bit then we should see it get started okay so now that server is going to reboot and that was triggered through our Python program so that's great the script is working well so far so let me go back to the script here so now let's take all that logic that we use to reboot our machine and move that into our conditional for if our website isn't returning a response code of 200 so I'm going to take just these three lines here and cut those out and now I'm going to uncomment out what we had before where we sent our email and actually I'm not sure at what point this got uninvented here it was probably whenever I checked it to send the email but this should actually be indented here within this context manager so we want to push that here within the width statement okay but after that email is sent let's go down here and we want to backspace to where we are not within that context manager now I'm going to paste in those lines get this indentation correctly here let me just put all of these together since they are logically the same so we're connecting to that low note client loading up the instance and rebooting that server and that is all within the conditional of if our status code is not equal to 200 now if you're wondering how I knew how to use the low note Python library really you just have to take the time to read through the documentation on stuff like that there's a lot more that you can do with that API if you're interested honestly this is basically all that I've used that library for so I'm interested in learning more about it myself okay so now we have a script that should send us an email and restart our server if our site doesn't respond with a 200 code so now let's test this out so in order to test this let me change the URL that I'm requesting to a page that won't respond with a 200 response so for example just let me go to a route that doesn't exist and that's going to return a 404 response and since that isn't a 200 response then it should send me an email and then restart my server so I'm just going to go up here and change the route that we're trying to connect to and I'm just going to do a forward slash DNA 4 does not exist so if I run this then we don't get any output here but if I check my email I'm looking at my email here on my phone and that email did come through that said your site is down make sure that the server restarted and is back up so if I go back to Milan ode page here then we can see that this reboot has already started on that machine so it's rebooting again so it does look like our site worked in that sense and we also get 'la note notifications here that tell us when these servers are rebooting so we can see one was five minutes ago and one was a few seconds ago and then four days ago from when I was testing the script okay so now let me go back to our script here now one thing that I could probably add to the script is some feedback or logging so that we can see when events like this are triggered but for now I can just expect an email and can also look at Milan ode to see if it's rebooting okay so now that I know that works I'm going to set this page back here to a to my home page rather than a page that doesn't exist okay so there's actually one more thing that we need to do with this script here so right now we are sending in the email and restarting the server if we don't get a status code of 200 but sometimes we won't even get a status code at all it's possible that requests not get is going to throw an exception so for example if it times out it's going to throw an exception or if the server is down completely then it's going to throw an exception and we are not handling that right now so what we're gonna do let's put in a try except block to where if there's any exceptions then we go ahead and send this email and restart the server and also if we do get a response code then we'll check if that is a 200 response or not so I think the best thing to do here is to move all of this functionality into a function so that we can run this in multiple scenarios so here at the top of my script underneath my environment variables I'm going to create two different functions here so I'll call one of these let's see notify user something like that and I don't think we need any arguments into this function I'm just going to take all of our email stuff here and I will cut that out and I'm going to put all of that here within this notify user function so now and we could add arguments to this function if we wanted to so for example you know we could put a custom sender and receiver here for the email something like that all of this is just hard coded into this script for my personal example so I'm just gonna leave it as is but if you wanted to customize it and make this you know more customizable then you could add those in here okay so I'm going to call

Notify User

that notify user and then I will create another function here and I will call this reboot server and again I'm just going to take the code from there and put it into this function here so now I can just say when our status code is not equal to 200 we want to notify the user and we want to reboot the server and now that we have those in functions now we can also check if we get an exception and do the same thing if we hit an exception here so I'm going to create a try and accept block here so I'll just do a basic try except now I'm going to copy where we are doing this request and I will paste that into our try block so what we're doing is we are trying this code here and if we hit an exception and I'm just going to leave this as any exception there are different exceptions and you can you know get more in depth with this and more specific if you want but I'm just going to say if we hit any exception then that means that our request wasn't successful so I'm going to want to notify myself and I'm going to go ahead and try to reboot my server anyways so again what we're saying here is we are trying to make this request if we get an exception I want to send that email and reboot the server if that success or if we did get a response then we're checking ok this is the response that we got a 200 response if not then I want you to also send that email and reboot the server so to test this let me actually log into Milan ode and I will go ahead and just stop apache completely and that should cause us not to get a response at all and then we'll see and that will make an exception and then we'll see if it also sends the email and reboots our server in that case so let me try this out I'm actually SSH into Milan ode machine right here and this is my server and currently I have Apache running here so let me try to just stop Apache so I need to put in my password there now it says stopping web server so I just took down my personal website and now I shouldn't get any response at all so now let's try to run this code again and we don't get any output here oh actually we did get an error here yeah so I know what this is this was a dumb mistake some of you probably caught it before I even did it but if we get an error here then this but our variable here is never even going to be set to begin with so I'm gonna put this up here within my try block as well so now if we get an exception thrown on here then it's going to hop down here and send the email and reboot the server if we didn't get an exception that'll continue on and check the status code and send the email and reboot the server the reason that it threw an error when that was located outside of the try accept block is because if this is an error right here then that never gets set that our variable never gets set so when we were trying to access it down here it didn't know what it was okay so now let me try to save and run that script again now it probably did send that email and it probably did reboot my server because it still hit that exception before it ran into that error so let me check my email here well it really quick yet I can see that my site actually is down and if I go back to Milan ode it may have already restarted actually yes it did it was started two minutes ago so let's run this again and see if this works so I'll run that now we shouldn't get any output and if I check my email now this might actually not be down because when it restarted it probably restarted Apache as well so let me try to log back in to Milan Oh shut that down and try it one more time okay so I paused the video and I signed back in to Milan ode server here and now let me do the same thing again so when it restarted if I run Apache status once I restarted the server it started Apache again so let me stop that okay it stopped and now let's run the script again it's going to hit this exception and send the email okay so run this we don't get any output which is what we expect I'm looking at my phone here and I just got an email that says that my site is down and that the server is restarting so if we open this back up we just got a notification that a few seconds ago that we scheduled a reboot and we can see that the machine is rebooting here and down here I am getting this notification that I just got kicked out of my SSH session and that is because the server is now down but once that reboots then our website will be working so we can see here that my website is down because Apache was stopped and once this finishes rebooting then my site should be up so I'm gonna pause the video and wait for this to finish and then I'll go and try my website again okay so I paused the video there for a second and let the reboot finish and now I'm logged back into Milan ode server here and now if I check the Apache status now it is running so if I go back to my website here and try to reload this then now this loads up just the way it should everything is working nicely so we can see that's a nice feature there that if our Apache even shuts down for any reason whatsoever then it's just going to automatically try to restart so I think that is a pretty nice feature that we added in there okay so now I have a working script that I can run anytime that I want to check the status of my website and we'll perform those actions if there are any issues but what if I want to run this script every ten minutes or so that this process of checking the website is automated so I don't want to have to actually run this script manually every time I want to check my website the point is that something is monitoring our website for us so in order to do this we're going to need to use some sort of task scheduler now again I am on Mac oops this is I want to go ahead and exit that session there so like I was saying I am on a Mac so the task scheduler used on Mac and Linux is called cron now if you're on Windows then I believe it's actually called task scheduler so you can use the scheduler for your operating system but since I'm on a Mac I'm going to use cron so let's say that we want to run our website check every 10 minutes so first what command do we actually want to run so remember we created a virtual environment for our little project here now when we installed all those packages we installed them in our virtual environment so that is the version of Python that we need to run our script with so that it has access to those specific packages now we have our environment activated now but if we don't then we can simply run our script with the Python executable from that environment so to do this we just need to specify the path to that Python version so on my machine that would look like this so with the environment activated I can say which Python and we can see that it gives us the full path to the Python from that environment that is activated now this is just my home folder here so a short version of this I could just use a tilde and then copy the rest after this and if I run that then we can see that it just runs that version of Python so I can you know import requests and that should work because we have pip installed that inside that environment so that is the Python command that we're going to run and we're also going to want to specify the full path to the script as well since we don't want to rely on it being from a relative direct directory so on my machine the path to that script would be the home folder in site monitor and that is monitor whoops monitor dot py so the entire command if I paste in what I had before whoops let me put the home folder there so this is going to be the entire command that we're going to run every ten minutes so we have the full path to the Python executable for that virtual environment and the full path to the script that we want to run so if I run that then it just ran that script with that version of Python and we can see that ran very quickly and the reason that it ran very quickly is because it went out to my site and got a 200 response since the site is working and it didn't do any of the emails or restarts or anything like that so hopefully that's what it's going to do most often when it runs is just run very quickly like this okay so I'm going to copy this entire command and that's what I'm going to schedule to run every 10 minutes so on my machine I can access cron from the command line by saying crontab - e that's - II for edit and you can see that I don't currently have anything in my crontab right now by default cron opens up in the vim editor now if you aren't comfortable in them then you can change the editor to Nano or something like that now I felt like I've said this a lot during this video but I'm not going into the details of cron here but I do have a detailed video tutorial on using cron and I'll leave a link to that video in the description section below also if you'd like to learn more about cron in depth but for now let me just write out this cron schedule and then I'll explain exactly what it's doing so in vim if you want to insert something then you have to hit I first and we can see down here that it says insert so now I'm going to type out this schedule so for this schedule I'm going to do an asterisk ford slash tin space asterisks space asterisk space estrus space asterisks so basically the schedule that we have here will run our command every 10 minutes on every day of the year so the first value here is what minute we want to execute our command the asterisk forged slash means that we want to run this command every 10 minutes now the next value here the second asterisk is the value for the hour so our asterisk is saying that we want to run at every hour the next value is for the day of the month so this is every the next value is for the month so we set it to every month and the last value here is the day of the week so this is set to run on any day of the week so that's our schedule and this will run a command every 10 minutes so now let's tell it what command we want to run every 10 minutes so I copied that long command from my terminal from before and I'm just going to paste this in here ok and that is our entire cron schedule so now I just want to save this so in vim to save I can just press escape and that takes us out of insert mode and now I can press: WQ 4 whoops WQ 4 right and quit so I will run that it's going to tell me that this wants to do some administration I'll just click OK now it says installing new crontab and if you ever want to list out your crontab schedule then you can say crontab - l and that'll show us all of the commands that we are running and on what schedule okay so now that script should run every 10 minutes so that should be it now it would be nice to have some sort of feedback where we could go and check from time to make sure that our script is running so that's another reason why it would be a good idea to add some logging into that script so that we could occasionally check the logs and make sure that everything is running properly you know make sure that it goes out and makes the request and any time it runs into errors or anything like that and there's probably a lot more that we could add to that script as well but I think I'm happy with what I have here for now and if I need to add to it in the future then we can build from there now I will put this script up on github if anyone wanted to follow along but didn't necessarily want to write everything out here so I will have a link to this in github as well and again like I was saying before if you want to write a script like this that monitors one of your websites then you're gonna have to change some of the environment variables here so you're gonna have to have your email username and password to send the email and a token for whatever service you're using I'm using the node but I'm sure you know probably digitalocean and other services have something like this as well okay so I think that is going to do it for this video like I said this video is a bit different than the tutorial set I usually cover we didn't go into as much step-by-step detail here but I get a lot of requests from people who want me to record little scripts like this that are you know quick dirty solutions to some daily problems that I run into so that's really what I was shooting for here but if anyone has any questions about what we covered in this video then feel free to ask in the comment section below and I'll do my best to answer those and if you enjoy these tutorials and would like to support them then there are several ways you can do that the easiest way is to simply like the video and give it a thumbs up and also it's a huge help to share these videos with anyone you think would find them useful and if you have the means you can contribute through patreon and there's a link to that page in the description section below be sure to subscribe for future videos and thank you all for watching

Другие видео автора — Corey Schafer

Ctrl+V

Экстракт Знаний в Telegram

Экстракты и дистилляты из лучших YouTube-каналов — сразу после публикации.

Подписаться

Дайджест Экстрактов

Лучшие методички за неделю — каждый понедельник