What you need are a bunch of glass jars. If you don't have any and can't buy any affordably (look for canning jars, in many stores at this time of year) use clear plastic containers that seal tightly. You'll also need a permanent marker, and tape or labels if you want to be able to put other things in those containers later.
Inspect the entire outside of each unopened package for small holes (worms can chew thru many things), webs, sticky stuff, or funny-looking granules. Put any that look suspicious in a pile along w/all opened packages.
Next, for each package in your pile: Pour half the food into a jar. Tilt or stir the stuff and look for worms, eggs, webs, or anything other than the food. If you see any, throw it out. Inspect the other half of the food in the package, then add it to the jar. Then check inside the empty package. If all is well, label the jar.
Clean the inside of the affected cupboards. (I've always used vinegar for this, but I don't know if it actually does anything to repel the bugs.) Keep everything in jars or other tightly-closed unchewable packages for at least a few months, and the bugs will decide it's not a good habitat.